2015-12-28 94 views
2

我看過堆棧溢出,但每次我找到一段代碼,人們說會工作,很遺憾不適合我。Nginx的 - 重定向非ssl&非www到ssl&www

我在Forge上使用Laravel並嘗試將非www非ssl重定向到ssl + www。

它的工作原理。但是,它不會重定向https://example.com。它重定向所有其他的:example.com or www.example.com or http://example.com or http://www.examplehttps://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"; 
    } 

} 

回答

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

我收到服務器錯誤未找到 –

+0

我已經編輯我的答案。我認爲現在很好。 – Alex

+0

仍是同樣的問題。 Chrome顯示了這個:'DNS_PROBE_FINISHED_NXDOMAIN'。也許是因爲我必須在配置文件中監聽443?你的和我已經擁有的另一個? –