Nginx - 重定向非ssl&非www到ssl& WWW

时间:2015-12-28 18:09:05

标签: laravel ssl nginx

我已经查看了Stack Overflow,但每当我找到一段人们认为可行的代码时,遗憾的是它并不适用于我。

我在Forge上使用Laravel并尝试重定向非www&非ssl到ssl + www。

有效。但是,它不会重定向https://example.com。除了上面提到的内容之外,它会将所有其他人example.com or www.example.com or http://example.com or http://www.example重定向到https://www.example.com

我不知道为什么会这样。

这是我的Nginx文件:

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

 server {
    listen 80;
    server_name xxx.xxx.xxx.xxx;

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

server {
    listen 443 ssl;
    server_name example.com;
    root /home/forge/example.com/public;

    # FORGE SSL (DO NOT REMOVE!)
    ssl_certificate /etc/nginx/ssl/example.com/21671/server.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com/21671/server.key;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

    index index.html index.htm index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

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

    access_log off;
    error_log  /var/log/nginx/example.com-error.log error;

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }

    #cache:
    location ~* \.(css|js|gif|jpe?g|png)$ {
        expires 168h;
        add_header Pragma public;
        add_header Cache-Control "public, must-revalidate, proxy-revalidate";
    }

}

1 个答案:

答案 0 :(得分:0)

因为前两个服务器只收听帖子80(非ssl)。

像这样改变它们:

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

 server {
    listen 443 ssl;
ssl_certificate /etc/nginx/ssl/example.com/21671/server.crt;
ssl_certificate_key /etc/nginx/ssl/example.com/21671/server.key;
    server_name example.com;

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