Reputation: 8629
I'm hosted on Digital Ocean Ubuntu server.
I want to redirect my non-www traffic to www. All using https.
Here's what I have for /etc/nginx/sites-available/default
server {
if ($host = www.test.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
if ($host = test.com) {
return 301 https://www.$host$request_uri;
} # managed by Certbot
listen 80 default_server;
listen [::]:80 default_server;
server_name test.com www.test.com;
return 404; # managed by Certbot
}
However, it's not working. Can someone please help?
Upvotes: 1
Views: 1277
Reputation: 1085
You should not use 'if' to listen for requests. https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/
The Nginx manual for setting up servers: https://docs.nginx.com/nginx/admin-guide/web-server/web-server/
Here's an example to match your setup:
# catch all traffic to https://www.test.com
server {
listen 443 ssl http2;
server_name www.test.com;
#change this to your web root
root /home/test;
# specify index files
index index.php index.html index.htm;
#change this to your certificate paths and so on
ssl_certificate /etc/letsencrypt/live/test.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/test.com/privkey.pem;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
#this will look for a file, then a directory, finally for an index file, leave as is
location / {
try_files $uri $uri/ /index.php?$query_string;
}
#change this to match your php setup
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass 127.0.0.1:9000;
}
}
# redirect all https traffic from non www tot www, you need a certificate here
server {
listen 443 ssl;
server_name test.com;
return 301 https://www.test.com$request_uri;
#change this to your certificate paths
ssl_certificate /etc/letsencrypt/live/test.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/test.com/privkey.pem;
}
# redirect all traffic from http to https
server {
listen 80;
server_name www.test.com test.com;
return 301 https://$host$request_uri;
}
Upvotes: 2