3

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:)

Ning Lv
  • 35
  • 1
  • 5

2 Answers2

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 tell me the version of your nginx and your os name – oakymax Jul 27 '16 at 04:57
  • @ Maxim Korshunov nginx version: nginx/1.5.6 , os version:centos 4.3 – Ning Lv Jul 27 '16 at 11:14
  • @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

  • 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