Nginx rewrite and redirect are two different concepts used to manipulate URLs and control how web server requests are processed. Here’s a breakdown of the differences between them:
-
Nginx Rewrite:
- Rewriting in Nginx refers to changing the URL internally before processing the request.
- It doesn’t send an HTTP redirect response to the client’s browser.
- Rewrites are often used for URL rewriting, URL mapping, or internal routing within your web server configuration.
- A common use case is to rewrite URLs to make them more user-friendly or to adapt them to the server’s internal file structure.
Example:
location /old-url { rewrite ^/old-url(.*)$ /new-url$1 last; }
In this example, any request to “/old-url” will be internally rewritten to “/new-url,” and the client is not aware of this change.
-
Nginx Redirect:
- A redirect in Nginx involves sending an HTTP response (usually a 3xx status code) to the client’s browser, instructing it to make a new request to a different URL.
- Redirects are typically used for scenarios like URL changes, moving content to a new location, or enforcing HTTPS.
- Redirects inform the client’s browser to make a new request to the specified URL, which may result in an additional HTTP round trip.
Example:
location /old-url { return 301 /new-url; }
In this example, when a client requests “/old-url,” Nginx sends a 301 (Permanent Redirect) response, instructing the client’s browser to request “/new-url.”
In summary, Nginx rewrite is used for internal URL manipulation without involving the client’s browser, while Nginx redirect is used to instruct the client’s browser to make a new request to a different URL. The choice between them depends on your specific use case and the behavior you want to achieve.
Comments