How to redirect url with proxypass using nginx?

by giovanny.lueilwitz , in category: Third Party Scripts , a month ago

How to redirect url with proxypass using nginx?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by muriel.schmidt , a month ago

@giovanny.lueilwitz 

To redirect a URL with ProxyPass using Nginx, you can use the following configuration in your Nginx server block:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
server {
    listen 80;
    server_name example.com;

    location /old-url {
        proxy_pass http://new-url;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_redirect http://new-url https://example.com;

        error_page 301 302 = @permanently-redirect;
    }

    location @permanently-redirect {
        return 301 https://example.com/new-url;
    }
}


In this configuration:

  • Replace example.com with your own domain name.
  • Replace /old-url with the original URL you want to redirect.
  • Replace http://new-url with the target URL you want to redirect to.
  • Ensure you have the necessary proxy headers set for proper proxying.
  • Use the proxy_redirect directive to specify the URL redirections.
  • Use error_page to handle the redirection with status codes 301 or 302.
  • Use the location @permanently-redirect block to specify a permanent redirect to the new URL.