Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect HTTP to HTTPS from Nginx is not working

Tags:

nginx

https

ssl

Type: https://example.com => ssl ok But type: www.example.com and example.com is http no redirect https. (www redirect to non-www).

WordPress Address (URL) and Site Address (URL): https//example.com

/etc/nginx/conf.d/example.com.conf

server {
listen 80; 
server_name example.com www.example.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl;
server_name example.com www.example.com;
ssl on;
ssl_certificate /etc/nginx/ssl/cert_chain.crt;
#ssl_CACertificate_File /etc/nginx/ssl/example.com.ca-bundle;
ssl_certificate_key /etc/nginx/ssl/example.com.key; 
access_log off;
# access_log /home/example.com/logs/access_log;
error_log off;
# error_log /home/example.com/logs/error.log; 
add_header X-Frame-Options SAMEORIGIN;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
root /home/example.com/public_html;
include /etc/nginx/conf/ddos2.conf;
index index.php index.html index.htm;
server_name example.com;

How to fix it ? Sorry my bad English, thank you.

like image 517
Huu Duc Cua Hang Avatar asked Oct 20 '25 15:10

Huu Duc Cua Hang


2 Answers

This might be caused by the ambiguous server name indeed. Try using the following:

server {

    server_name example.com www.example.com;
    listen 80;
    listen 443 ssl; # Listen for SSL at port 443 as well

    # ... other config - certificates and such

    # If a user tries to come through http, redirect them through https
    if ($scheme != "https") { 
        return 301 https://$host$request_uri;
    }
}

You can check your nginx configuration by running sudo nginx -t.

like image 93
Heehaaw Avatar answered Oct 23 '25 04:10

Heehaaw


I had the similar problem. It was caused by linux firewall (port 80 was disallowed).

like image 21
Dm Dm Avatar answered Oct 23 '25 05:10

Dm Dm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!