Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx redirect to www domain not working

Tags:

nginx

I have the following nginx configuration.

server {
    listen 80;
    listen [::]:80;
    listen 443 ssl;
    server_name example.com;
    return 301 https://www.example.com$request_uri;
}
  • it redirects http://example.com to https://www.example.com
  • but does not redirect https://example.com to https://www.example.com.

How can I redirect https://example.com to https://www.example.com?

like image 396
Tony Joseph Avatar asked Jan 30 '16 05:01

Tony Joseph


People also ask

How do I redirect www Nginx to https?

Nginx Redirect all HTTP traffic to HTTPS Here is a breakdown of the commands: Listen 80 : This instructs the system to catch all HTTP traffic on Port 80. Server_name _; : This will match any hostname. Return 301 : This tells the browser (and search engines) that this is a permanent redirect.

How do I redirect a URL in Nginx?

To redirect a URL in a website running on an Nginx server, you must manually create a redirects. conf file. In this file will then add your redirect code.

What is the difference between 301 and 302 redirect?

There is a simple difference between a 301 and 302 redirect: a 301 redirect indicates that a page has permanently moved to a new location, meanwhile, a 302 redirect says that the page has moved to a new location, but that it is only temporary.


1 Answers

please separate http and https traffic. your current config is messing up a bit with things. The following code rewrites all request from http://example.com to https://example.com using a permanent redirect:

server {
   listen 80;
   server_name example.com;
   return 301 https://$server_name$request_uri;
}

Second code block will handle the request coming in from port 443 (example here will give you an A rating on ssllabs.com):

server {
   listen 443 ssl;
   server_name example.com;

   ssl_certificate /path_to/ssl.crt;
   ssl_certificate_key /path_to/ssl.key;
   ssl_session_timeout 1d;
   ssl_session_cache shared:SSL:10m;
   # ssl_session_tickets off;

   # openssl dhparam -out dhparam.pem 2048
   # ssl_dhparam /etc/nginx/SSL/dhparams.pem;

   ssl_protocols TLSv1.1 TLSv1.2;
   ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGC$
   ssl_prefer_server_ciphers on;

   add_header Strict-Transport-Security "max-age=15768000;includeSubdomains; preload";

   root /srv/wwwroot/;
   index index.html index.htm index.php;

   client_max_body_size 20M;

   location / {
       # your special config if needed
   }


 }

and finally with a third block in our config we rewrite https://www.example.com back to https://example.com :

server {
   listen 443;
   server_name www.example.com;
   return 301 https://$server_name$request_uri;
}

Hope this helps.

like image 65
semm0 Avatar answered Oct 17 '22 18:10

semm0