从Nginx将HTTP重定向到HTTPS无效

时间:2017-10-16 07:44:27

标签: ssl nginx https

输入:https://example.com => ssl ok 但请键入:www.example.com和example.com是http 无重定向 https。 (www重定向到非www)。

WordPress地址(URL)和站点地址(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;

如何解决? 对不起我的英文不好,谢谢。

4 个答案:

答案 0 :(得分:1)

这可能是由于模糊的服务器名称确实造成的。请尝试使用以下内容:

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;
    }
}

您可以通过运行sudo nginx -t来检查您的nginx配置。

答案 1 :(得分:1)

我有类似的问题。这是由linux防火墙引起的(不允许使用端口80)。

答案 2 :(得分:0)

您的配置不明确,最后您有一条重复的server_name example.com行。

尝试使用它:

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

答案 3 :(得分:-1)

您好,请尝试使用此代码

它可以帮助您重定向到https 说你输入http://www.example.com会重定向到https://www.example.com
此外,如果有人输入http:example.com将重定向到https://www.example.com
<VirtualHost *:80> ServerName www.example.com DocumentRoot /usr/local/apache2/htdocs Redirect permanent / https://www.example.com/ </VirtualHost> <VirtualHost_default_:443> ServerName www.example.com DocumentRoot /usr/local/apache2/htdocs SSLEngine On RewriteCond %{HTTPS} off RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ RewriteRule (.*) https://www.example.com/$1 [R=301,L] RewriteCond %{HTTPS} off RewriteCond %{HTTP_HOST} ^example\.com$ RewriteRule (.*) https://www.example.com/$1 [R=301,L] </VirtualHost>