I’m trying to make my nginx server to redirect any www request to non www. On nginx server, i run react application on 3003 port using docker.
Here is my config:
server {
server_name www.example.com; # managed by Certbot
location / {
proxy_pass http://localhost:3003; # 8030 is the port the Docker container is running on
proxy_set_header Host $host;
#try_files $uri $uri/ =404;
}
listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = www.example.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
if ($host = www.example.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80 ;
listen [::]:80 ;
server_name example.com www.example.com;
return 404; # managed by Certbot
}
Any ideas how to do that?
4
Answers
So, after few hours of searching, i finally found the solution! Here is the code:
Add this to your server directive, adapt the website url
If you want redirect users from www to a plain, non-www domain, insert this configuration:
Save and exit. This configures Nginx to redirect requests to “www.example.com” to “example.com”. Note that there should be another server block that defines your non-www web server.
To put the changes into effect, restart Nginx:
Note that if you are using HTTPS, the listen directive should be set to port 443 instead of 80.
Use this curl command to ensure that the non-www domain redirects to the www domain (replace the highlighted part with your actual domain):
You should get a 301 Moved Permanently response, that shows the non-www redirect location, like this:
Of course, you should access your domain in a web browser (www and non-www) to be sure. For more detail you can access this link:
https://www.digitalocean.com/community/tutorials/how-to-redirect-www-to-non-www-with-nginx-on-centos-7
You can just use the map instead of if to extract part of the $host value like this following:
In this case map directive extract the value of $tld which doesn’t contain www. part of the URL