Question

Nginx Force Redirection Not Working

I’m facing a huge problem configuring redirection with Nginx.

My nginx configuration is this;

server {
   listen 80 default_server;
   listen 443 ssl default_server;

   ssl_certificate /var/www/html/.v/example.crt;
   ssl_certificate_key /var/www/html/.v/example_private_key.key;
   return 301 https://www.example.com$request_uri;
}

server {

    listen 443 ssl;
    server_name www.example.com example.com;
    root /var/www/html/mova;
    index index.php index.html index.htm;
    charset UTF-8;
    ssl_certificate /var/www/html/.v/example.crt;
    ssl_certificate_key /var/www/html/.v/example_private_key.key;
   
   
    location / {
	
        try_files $uri/ /index.php?$args;
     }

	location ~ /.v {
          allow all;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        fastcgi_index index.php;
        include fastcgi.conf;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico|eot|otf|ttf|woff)$ {
       add_header Access-Control-Allow-Origin *;
       access_log off; log_not_found off; expires 30d;
     }

    client_max_body_size 40M;

     location = /robots.txt { access_log off; log_not_found off; }

     location ~ /\. { deny all; access_log off; log_not_found off; }

}

In my WordPress and site address url:

   https://www.example.com

My DNS settings I only created A record for example.com with my vps ip address as the value.

The problem is when I put example.com in the url bar, it will take me to http://example.com, and when I put https://www.example.com, it will take me to https://www.example.com.

Now, what I want is this, I want all url to redirect to https://www.example.com.


Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.

What you’ll want to do is move www.example.com into its own server block that is configured to redirect all requests to example.com. So, remove www.example.com from the existing server_name and add the following block:

server {
    listen 80;
    listen 443 ssl;
    ssl_certificate /var/www/html/.v/example.crt;
    ssl_certificate_key /var/www/html/.v/example_private_key.key;

    return 301 https://example.com$request_uri;
}