I have nginx and I want to redirect non-www to www:
So I did it using regex, but the redirect seems to works I get the redirect, but www return timeout.
How can I solve this?
upstream wwwapp {
least_conn;
server www-app:3000 weight=10 max_fails=3 fail_timeout=30s;
}
server {
server_name ~^(?!www\.)(?<domain>.+)$;
return 301 $scheme://www.$domain$request_uri;
}
server {
listen 80;
location / {
proxy_pass http://wwwapp;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
Easy.
server {
listen 80;
if ($host ~ ^(?!www\.)(?<domain>.+)$) {
return 301 $scheme://www.$domain$request_uri;
}
location / {
proxy_pass http://wwwapp;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
Your second server block does not have a server_name so it is unlikely to get selected to process any requests.
The first server block is the default and will get selected even if the regex does not match.
You should change the second server block, and either add a server_name statement or make it the default_server.
See this document for details.