Nginx: Hot to redirect www domain to not www
In this super short note, I will show you how to redirect from the old-style www.yourdomain.com to the modern yourdomain.com.
Simply add the following code before your Nginx domain config to make the necessary changes:
server {
listen 80;
server_name www.yourdomain.com;
return 301 https://yourdomain.com$request_uri;
}
Here complete file view for better understanding:
server {
listen 80;
server_name www.yourdomain.com;
return 301 https://yourdomain.com$request_uri;
}
server {
root /var/www/yourdomain.com;
index index.php index.html index.htm;
server_name yourdomain.com;
location / {
#try_files $uri $uri/ =404;
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
}
There are a few reasons why it is generally preferred to use a non-www domain configuration:
- Simplicity: A non-www domain is shorter and easier to remember, making it more convenient for users.
- Consistency: Using a non-www domain allows for a consistent brand experience across all web pages, as there is no need to worry about redirecting www pages to non-www pages.
- SEO: Some search engines may treat www and non-www pages as separate entities, which can impact your search engine ranking. By choosing a non-www configuration, you can avoid any potential SEO issues.
- Improved user experience: A shorter and simpler domain can lead to a better user experience, as users are more likely to remember it and return to your site in the future.