Home > OS >  How do I use nginx to rewrite all links start with www.example.com/page to www.example.com/new-page
How do I use nginx to rewrite all links start with www.example.com/page to www.example.com/new-page

Time:02-14

I want to redirect all request to

www.example.com/page

to

www.example.com/new-page

That means to replace www.example.com/page with the new one, for instance:

www.example.com/page
301 > www.example.com/new-page

www.example.com/page/1
301 >www.example.com/new-page/1

www.example.com/page/1.png
301 >www.example.com/new-page/1.png?1

www.example.com/page/common/1.png
301 >www.example.com/new-page/common/1.png?1

www.example.com/page123
301 >www.example.com/new-page123

How could I do that?

CodePudding user response:

Use rewrite with a redirect param like

location /page/ {
        rewrite ^/page/(.*)$ /new-page/$1 permanent;
    }

My Testing

127.0.0.1 - - [12/Feb/2022:10:20:42  0000] "GET /page/test/123 HTTP/1.1" 301 169 "-" "curl/7.74.0" "-"
* Mark bundle as not supporting multiuse
< HTTP/1.1 301 Moved Permanently
< Server: nginx/1.21.6
< Date: Sat, 12 Feb 2022 10:20:42 GMT
< Content-Type: text/html
< Content-Length: 169
< Location: http://127.1/new-page/test/123
< Connection: keep-alive
<
* Ignoring the response-body
* Connection #0 to host 127.1 left intact
* Issue another request to this URL: 'http://127.1/new-page/test/123'
* Found bundle for host 127.1: 0x561d293f5970 [serially]
* Can not multiplex, even if we wanted to!
* Re-using existing connection! (#0) with host 127.1
* Connected to 127.1 (127.0.0.1) port 80 (#0)
> GET /new-page/test/123 HTTP/1.1
> Host: 127.1
> User-Agent: curl/7.74.0
> Accept: */*
>127.0.0.1 - - [12/Feb/2022:10:20:42  0000] "GET /new-page/test/123 HTTP/1.1" 200 3 "-" "curl/7.74.0" "-"

* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Server: nginx/1.21.6
< Date: Sat, 12 Feb 2022 10:20:42 GMT
< Content-Type: application/octet-stream
< Content-Length: 3
< Connection: keep-alive
<
OK
  • Related