If you are running a web server with Nginx, you may want to redirect incoming requests to a specific URL format. For example, you may want to redirect all requests for http://example.com
to http://www.example.com
, or vice versa. In this article, we will show you how to redirect non-www and www URLs on Nginx.
- To redirect non-www and www URLs on Nginx, you need to edit the
server
block configuration file for the domain that you want to redirect. The location of the configuration file depends on your Nginx installation and configuration, but it is usually located in the/etc/nginx/sites-enabled
directory. For example, if you want to redirect theexample.com
domain, you would edit the/etc/nginx/sites-enabled/example.com
file. - Open the configuration file in a text editor, and add the following code to the
server
block:
server {
listen 80;
server_name example.com www.example.com;
return 301 http://www.example.com$request_uri;
}
This code will redirect all requests for the example.com
and www.example.com
domains to http://www.example.com
.
- If you want to redirect requests for the
www.example.com
domain to theexample.com
domain instead, you can use the following code in theserver
block:
server {
listen 80;
server_name example.com www.example.com;
return 301 http://example.com$request_uri;
}
This code will redirect all requests for the example.com
and www.example.com
domains to http://example.com
.
To apply the changes, you need to restart the Nginx service. Run the following command to restart Nginx:
sudo systemctl restart nginx
This will apply the changes that you made to the server
block configuration file, and redirect incoming requests to the specified URL format.
In this article, we have shown you how to redirect non-www and www URLs on Nginx. By redirecting requests to a specific URL format, you can ensure that your users always access your website using the correct URL, and avoid any confusion or errors. For more information about configuring Nginx, you can refer to the Nginx documentation.