Answer the question
In order to leave comments, you need to log in
How to set up a 301 redirect from www to non-www in nginx for all pages?
Good afternoon. Please tell me, in fact, the redirect from www to without www works for me, but the 301 code does not give back, but it needs to give it back.
Here he wrote:
server {
if ($host = www.dev.site.ru) {
return 301 https://$host$request_uri;
} # managed by Certbot
if ($host = dev.site.ru) {
return 301 https://$host$request_uri;
} # managed by Certbot
server_name dev.site.ru www.dev.site.ru;
listen 80;
return 404; # managed by Certbot
}
server {
root /var/www/dev.site.ru/public_html/;
server_name dev.site.ru www.dev.site.ru;
index index.php;
location ~* \.(js|css|png|jpg|jpeg|gif|ico|html)$ {
access_log off;
log_not_found off;
expires max;
}
location / {
# add_header Access-Control-Allow-Origin *;
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
try_files $uri = 404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/dev.site.ru/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/dev.site.ru/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
include /var/www/dev.site.ru/public_html/nginx.conf;
}
server {
if ($host = www.dev.site.ru) {
return 301 https://$host$request_uri;
} # managed by Certbot
if ($host = dev.site.ru) {
return 301 https://$host$request_uri;
} # managed by Certbot
server_name dev.site.ru www.dev.site.ru;
listen 80;
return 404; # managed by Certbot
}
server {
server_name www.dev.site.ru;
return 301 https://dev.site.ru$request_uri;
}
Answer the question
In order to leave comments, you need to log in
You need three sections server{}
One for port 80 with server_name dev.site.ru www.dev.site.ru ; and return 301 https://dev.site.ru$request_uri ;
One for port 443 with server_name www.dev.site.ru ;, certificates and return 301 https://dev.site.ru$request_uri ;
Another one at 443 from server_name dev.site.ru ; and the main part of your config.
In your case, the added section intersects by port (80) and the server_name(www.dev.site.ru) part with the section added by certbot.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question