I'm new to Nginx and trying to figure out how to properly handle subdomains. What I want to achieve is that the main domain example.com
is always redirected to https://www.example.com
, but subdomains as sub.example.com
should always be redirected to https://sub.example.com
. In my current setup the first requirement is fulfilled, but sub.example.com
always gets redirected to https://www.sub.example.com
. What is the problem with my configuration and how can I fix it?
Thanks in advance, Fabian.
default
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
return 301 https://www.$host$request_uri;
}
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /path/on/my/server/to/certificate.pem;
ssl_certificate_key /path/on/my/server/to/privatekey.pem;
return 301 https://www.$host$request_uri;
}
server {
listen 443 default_server ssl http2;
listen [::]:443 default_server ssl http2;
server_name www.example.com;
ssl_certificate /path/on/my/server/to/certificate.pem;
ssl_certificate_key /path/on/my/server/to/privatekey.pem;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
location / {
try_files $uri $uri/ =404;
index index.php index.html index.htm;
}
}
sub
server {
listen 80;
listen [::]:80;
server_name sub.example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name sub.example.com;
ssl_certificate /path/on/my/server/to/subcertificate.pem;
ssl_certificate_key /path/on/my/server/to/subprivatekey.pem;
root /var/www/sub;
location / {
index index.php index.html index.htm;
try_files $uri = 404;
}
location ~ \.php$ {
try_files $uri = 404;
include fastcgi_params;
fastcgi_pass unix:/var/run/php7-fpm-web1.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
}
}
If this problem happens to anyone else: Try to clean your browser cache.