Reputation:
Here is what happens:
example.com -> https://example.com
http://example.com -> https://example.com
www.example.com -> -> https://www.example.com
This is what I want:
example.com -> https://www.example.com
http://example.com -> https://www.example.com
www.example.com -> -> https://www.example.com
What am I missing in my Nginx config? I cannot find out from all similarly asked questions. Some answers say to use an "if" statement, but Nginx doc says specifically not to do this because it will apply to ALL requests.
server {
listen 80;
listen 443; # add this line
server_name example.com;
return 301 https://www.example.com$request_uri;
}
server {
listen 80;
root /var/www/html;
index index.php;
server_name example.com www.example.com;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
Upvotes: 2
Views: 1865
Reputation: 675
Remove example.com
in server_name
of second block and add listen 443
to second block.
Hope it helps.
server {
listen 80;
listen 443; # add this line
server_name example.com;
return 301 https://www.example.com$request_uri;
}
server {
listen 80;
listen 443; # add this line too.
root /var/www/html;
index index.php;
# Remove example.com
server_name www.example.com;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
Upvotes: 2