To redirect an old domain to a new domain with an HTTP 301 Moved Permanently header in Nginx, you can use the server_name
directive and the return
or rewrite
directive inside the server
block in the Nginx configuration file.
For example, to redirect all requests for http://old-domain.com
to http://new-domain.com
, you can add the following configuration to your Nginx configuration file:
server { listen 80; server_name old-domain.com; return 301 http://new-domain.com$request_uri; }
This will redirect all requests for http://old-domain.com
to http://new-domain.com
with an HTTP/1.1 301 Moved Permanently header.
Alternatively, you can use the rewrite
directive to achieve the same result:
server { listen 80; server_name old-domain.com; rewrite ^ http://new-domain.com$request_uri permanent; }
Keep in mind that you will need to reload or restart Nginx for the changes to take effect.
service nginx reload
Note: If you want to redirect specific URLs or paths within the old domain to specific URLs or paths within the new domain, you can use the location
directive and the return
or rewrite
directive inside the server
block.
For example, to redirect http://old-domain.com/old-path
to http://new-domain.com/new-path
, you can use the following configuration:
server { listen 80; server_name old-domain.com; location /old-path { return 301 http://new-domain.com/new-path; } }
server { listen 80; server_name old-domain.com; location /old-path { rewrite ^ http://new-domain.com/new-path permanent; } }
This will redirect all requests for http://old-domain.com/old-path
to http://new-domain.com/new-path
.