for example, i want to redirect from https://www.example.com/${pid}.txt to http://www.anotherExample.com/api?pid=${pid} how to configure it in nginx? Thanks in advance:)
Asked
Active
Viewed 9,178 times
3
-
see this http://lethain.com/rewriting-parameterized-urls-with-nginx/ – Tony Vincent Jul 22 '16 at 04:04
-
Possible duplicate of [How to redirect a url in NGINX](http://stackoverflow.com/questions/10294481/how-to-redirect-a-url-in-nginx) – Jonathan Eustace Jul 22 '16 at 04:05
2 Answers
3
Try this:
server {
listen 443;
server_name www.example.com;
location ~* ^/(.+)\.txt$ {
return 301 http://www.anotherexample.com/api?pid=$1;
}
}
If your pid
have a specific format (only digits for example) then replace (.+)
with appropriate pattern.
If you want to display content without redirecting then replace return 301
with proxy_pass
.

oakymax
- 1,454
- 1
- 14
- 21
-
i use location ~ ^/([^/.]*).txt$ { return 301 http://www.anotherexample.com/api?pid=$1; } but it say 502 errors, and can't find anything useful in error.log, any idea? – Ning Lv Jul 26 '16 at 12:31
-
@NingLv tested - regexp works fine in my environment. Did you added https params? Try first on `http://` with `listen 80;`. – oakymax Jul 26 '16 at 12:42
-
@NingLv also you can try escaping backslashes: `\/` instead of `/`. This depends on nginx version – oakymax Jul 26 '16 at 12:48
-
@NingLv pls let me know when you'll get working config. Or just update this answer. This can be helpful for somebody else – oakymax Jul 26 '16 at 12:56
-
for comparation, just use server { listen 443; server_name www.anotherexample.com; location ~ ^/([^/.]*).txt$ { proxy_pass http://www.anotherexample.com/api?pid=$1; } } and still can get a 502 error, and if i don't use regex, location /123.txt { proxy_pass http://www.anotherexample.com/api?pid=123; } and it works fine, and i change another regex expression, still not work. so confused... why regex not working on my nginx? – Ning Lv Jul 27 '16 at 03:05
-
-
-
@NingLv I use nginx v1.10. The answer updated: regexp simplified, added . escaping before `txt` (this was mistake), and `~` to `~*`, try now. – oakymax Jul 27 '16 at 19:08
1
the best way is with a return 301
, it will redirect the request to the site you are setting to, perhaps it will be better make a return 301 $scheme://www.anotherexample.com/api?pid=$1;
, in this way your URL will be redirected as a HTTPS when you purchase and install an SSL

Juan José Albán
- 11
- 1
-
i use location ~ ^/([^/.]*).txt$ { return 301 http://www.anotherexample.com/api?pid=$1; } but it say 502 errors, and can't find anything useful in error.log, any idea? – Ning Lv Jul 26 '16 at 12:31