Redirect with nginx (remove substring from url)

4.2k Views Asked by At

I want do a redirect from old url:

http://example.org/xxxxxxxxx.html

To new urls (remove ".html")

http://example.org/xxxxxxxxx

How I can do this with nginx?

EDIT:

xxxxxxxxx can be differ, example:

http://example.org/url-1.html redirect to http://example.org/url-1 http://example.org/another-url.html redirect to http://example.org/another-url

3

There are 3 best solutions below

0
cnst On BEST ANSWER
location ~ ^(.*)\.html$ {
    return 301 $1;
}
1
Amarpreet Singh On

Probably you need a rewrite statement

location /xxx.html {
   rewrite ^/xxx(.*) http://example.org/xxxxx permanent;
 }

You detailed explanation please refer https://www.nginx.com/blog/creating-nginx-rewrite-rules/

Another method would be return directive

server {
    listen 80;
    listen 443 ssl;
    server_name www.old-name.com old-name.com;
    return 301 $scheme://www.new-name.com;
}
0
nPcomp On
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name example.org www.example.org;
    return 301 http://$server_name$request_uri;
}