Nginx

重定向 301 問題 Apache 在 Nginx 後面

  • December 6, 2017

我的非 wwwexample.com已重定向到www.example.com/index.php.

注意:我使用.htaccessnginx 虛擬主機文件而不是使用 nginx 虛擬主機文件進行重定向。

RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule (.*) http://www.example.com/$1 [L,R=301]

如果我評論這些行.htaccess並嘗試通過 nginx 虛擬主機文件重定向 curl 按設置正確響應,但我在訪問時收到 404(我的站點的模型)www.example.com

.htaccess順便說一句,通過nginx 或 nginx重定向這個更好嗎?因為我使用 nginx 作為代理。

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



location / {
   try_files $uri $uri/ @proxy;
}

location @proxy {
   proxy_pass http://127.0.0.1:8080;
   proxy_set_header Host $host;
   proxy_set_header X-Real-IP $remote_addr;
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_set_header X-Forwarded-Proto $scheme;
}

location ~ \.php$ {
   proxy_pass http://127.0.0.1:8080;
   proxy_set_header Host $host;
   proxy_set_header X-Real-IP $remote_addr;
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_set_header X-Forwarded-Proto $scheme;
}
}

虛擬主機程式碼 Nginx

server {
server_name example.com;
return 301 $scheme://www.example.com$request_uri;
}

curl -I example.com

HTTP/1.1 301 Moved Permanently
Date: Mon, 04 Dec 2017 20:39:54 GMT
Content-Type: text/html
Connection: keep-alive
Set-Cookie: __cfduid=d7048cb8bebb2c847d904c46cd78d8f0c1512419; 
expires=Tue, 04-Dec-18 20:39:54 GMT; path=/; domain=.example.com; HttpOnly
Location: http://www.example.com/
Server: cloudflare-nginx
CF-RAY: 3c8193e88245-EWR

所有站點都執行良好,但僅在索引處我收到 403 Forbidden。注意:這是一個內部重定向,所以我不知道哪個 nginx 或 apache 的性能更好。在 apache 中,非 www 被重定向到 www.example.com/index.php (我不希望這個 .index.php 並且在 nginx 中被正常重定向,但我在首頁上收到 403,站點的其餘部分工作正常。

我將重定向放在同一個server {}塊中,我需要為主機放置一個單獨的server {}塊。example.com

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


server {
   listen 80;
   server_name www.example.com;

   location / {
       try_files $uri $uri/ @proxy;
   }

   location @proxy {
       proxy_pass http://127.0.0.1:8080;
       proxy_set_header Host $host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header X-Forwarded-Proto $scheme;
   }

   location ~ \.php$ {
       proxy_pass http://127.0.0.1:8080;
       proxy_set_header Host $host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header X-Forwarded-Proto $scheme;
   }
}

引用自:https://serverfault.com/questions/886526