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.akbalmaty.kz; # 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/akbalmaty.kz/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/akbalmaty.kz/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.akbalmaty.kz) {
return 301 https://$host$request_uri;
} # managed by Certbot
if ($host = akbalmaty.kz) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80 ;
listen [::]:80 ;
server_name akbalmaty.kz www.akbalmaty.kz;
return 404; # managed by Certbot
}
Any ideas how to do that?
CodePudding user response:
if ($host = 'www.yoursite.com' ) {
rewrite ^/(.*)$ http://yoursite.com/$1 permanent;
}
Add this to your server directive, adapt the website url
CodePudding user response:
If you want redirect users from www to a plain, non-www domain, insert this configuration:
server {
server_name www.example.com;
return 301 $scheme://example.com$request_uri;
}
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:
sudo systemctl 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):
curl -I http://www.example.com
You should get a 301 Moved Permanently response, that shows the non-www redirect location, like this:
Output:
HTTP/1.1 301 Moved Permanently
Server: nginx/1.4.6 (Ubuntu)
Date: Mon, 04 May 2015 18:20:19 GMT
Content-Type: text/html
Content-Length: 193
Connection: keep-alive
Location: http://example.com/
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
CodePudding user response:
You can just use the map instead of if to extract part of the $host value like this following:
map $host $tld {
default $host;
'~^www\.(?<domain>.*)$' $domain;
}
In this case map directive extract the value of $tld which doesn't contain www. part of the URL