NGINX Proxy_Redirect: How to Use It ?

Nginx

The proxy_redirect directive can be used to change the Location header in a 3xx status message. A 3xx status message is a redirect message, such as a 301 Moved Permanently or 302 Found message. The Location header tells the client where to go next.

 

Basically, This can be useful for a variety of purposes, such as:

  • Rewriting HTTP redirects to HTTPS
  • Changing the hostname in the Location header
  • Adding a trailing slash to the Location header

 

This guide by Fixwebnode will guide you through on how to use NGINX Proxy_Redirect.

 

What is the syntax for NGINX Proxy_Redirect ?

The syntax for the proxy_redirect directive is as follows:

proxy_redirect <from> <to>;

The <from> parameter is the value of the Location header in the 3xx status message. The <to> parameter is the new value for the Location header.

 

 

Examples of implementing NGINX Proxy_Redirect

 

1. Rewrite all HTTP redirects to HTTPS

The following directive would rewrite all HTTP redirects to HTTPS:

proxy_redirect http://example.com https://example.com;

This directive would change the following Location header:

Location: http://example.com/

To:

Location: https://example.com/

 

2. Modify the hostname in the Location header

The proxy_redirect directive can also be used to change the hostname in the Location header. For example, the following directive would change the hostname from example.com to www.example.com:

proxy_redirect http://example.com http://www.example.com;

 

 

3. Add a trailing slash to the Location header

Finally, the proxy_redirect directive can be used to add a trailing slash to the Location header. For example, the following directive would add a trailing slash to all Location headers:

proxy_redirect http://example.com http://example.com/;

 

The proxy_redirect directive is a powerful tool that can be used to change the behavior of a reverse proxy. By understanding how to use this directive, you can customize your reverse proxy to meet your specific needs.

 

 

Additional information on the proxy_redirect directive

Here are some additional things to keep in mind when using the proxy_redirect directive:

  • The proxy_redirect directive only affects 3xx status messages.
  • The proxy_redirect directive can be used in any location block, but it is most commonly used in the location / block.
  • The proxy_redirect directive can be used multiple times in the same location block.

Conclusion

In this guide, we have learned about the NGINX Proxy_Redirect directive. We have seen how this directive can be used to change the Location header in a 3xx status message. 

 

We have also seen how the proxy_redirect directive can be used to change the hostname in the Location header, or to add a trailing slash to the Location header.

Your Cart