Within Nginx, you can configure redirection rules via the configuration file to redirect requests from one domain to another. There are two primary methods to achieve redirection: using the return directive and the rewrite directive. Below are examples of both methods:
Using the return directive
The return directive is a relatively simple and recommended method for redirection. You can define a return directive within the server block to instruct Nginx to return a redirect for specific requests. Here is an example that redirects all requests from old-domain.com to new-domain.com:
nginxserver { listen 80; server_name old-domain.com; return 301 http://new-domain.com$request_uri; }
In this configuration, when users access old-domain.com, Nginx sends a response with a 301 status code (permanent redirect), informing users that the resource has been permanently moved to new-domain.com. The $request_uri variable ensures that the complete request URI is included in the redirect, meaning any additional paths or query strings will remain in the new URL.
Using the rewrite directive
The rewrite directive offers greater flexibility by matching and modifying the request URI based on regular expressions. Upon successful matching, you can specify a new URI and choose whether to perform an internal redirect or send a redirect response. Here is an example that redirects requests to a specific path to another domain:
nginxserver { listen 80; server_name old-domain.com; location /somepath/ { rewrite ^/somepath/(.*)$ http://new-domain.com/otherpath/$1 permanent; } }
In this example, Nginx only redirects requests whose path starts with /somepath/ to the /otherpath/ path under new-domain.com. The $1 is a regular expression capture group that captures the portion of the original request following /somepath/ and inserts it into the new URL. The permanent keyword indicates a 301 permanent redirect.
Important Considerations
- When using a 301 redirect, it indicates a permanent redirection, and search engines will update their indexes to reflect the new location. For temporary redirects, use the 302 status code.
- After modifying the Nginx configuration, reload or restart the service to apply changes. Use the
nginx -s reloadcommand to safely reload the configuration file. - When implementing redirects, consider SEO implications. Permanent redirects (301) are generally more SEO-friendly as they pass link weight to the new URL.
This covers the basic methods for redirecting requests to different domains using Nginx along with key considerations.