Nginx

Nginx - proxy_pass - 特定位置不起作用

  • October 7, 2014

我正在嘗試使用 proxy_pass 使用 Nginx 屏蔽遠端 URL

當瀏覽器 url 為saas.localhost/uk_staging時,我想載入staging.saas.localhost/ _

出於某種原因,saas.localhost中的位置不起作用,而對於不起作用,我的意思是該位置似乎被忽略了。

saas.localhost/uk_staging由應用程序處理,而不是來自staging.saas.localhost/_,在我看來,即使對於saas.localhost/uk_staging,使用的位置也是 location ~ .php$

我創建了第二個域t.saas.localhost,它按預期工作

t.saas.localhost域執行良好。

t.saas.localhost/uk_staging正在顯示staging.saas.localhost /_ t.saas.localhost/anything_else正在顯示google.co.uk/

這是我目前的 Nginx 配置:

server {
   listen 80;
   server_name   saas.localhost www.saas.localhost staging.saas.localhost;
   root /codebase/saas;
   index index.php index.html index.htm;

   location /uk_staging {
           #proxy_set_header Host $host;
           #proxy_set_header X-Real-IP $remote_addr;
           proxy_pass http://staging.saas.localhost/_;
   }

   if (!-e $request_filename) {
           rewrite ^(.*)$ /index.php?action=$1 last;
   }

   location ~ \.php$ {
           try_files $uri =404;
           fastcgi_pass unix:/tmp/php5-fpm.sock;
           fastcgi_index index.php;
           fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
           include fastcgi_params;
           fastcgi_read_timeout 600;
   }
}

server {
   listen 80;
   server_name  t.saas.localhost;
   root /codebase/saas;
   index index.php index.html index.htm;
   location /uk_staging {
           #proxy_set_header Host $host;
           #proxy_set_header X-Real-IP $remote_addr;
           proxy_pass http://staging.saas.localhost/_;
   }
   location / {
           #proxy_set_header Host $host;
           #proxy_set_header X-Real-IP $remote_addr;
           proxy_pass http://google.co.uk;
   }
}

為什麼要使用指令重定向到同一個虛擬主機proxy_pass?!

此外,nginx 會以您可能沒想到的方式選擇匹配位置。閱讀本文:Nginx 重寫規則 403 錯誤

if可以避免時最好不要使用。

server {
   listen 80;
   server_name   saas.localhost www.saas.localhost staging.saas.localhost;
   root /codebase/saas;
   index index.php index.html index.htm;

   location ^~ /uk_staging {
           #proxy_set_header Host $host;
           #proxy_set_header X-Real-IP $remote_addr;
           proxy_pass http://staging.saas.localhost/_; # What are you doing here ??!!
   }

   #avoid rewrite for static content
   location ~* \.(js|jpg|png|css|htm|html|gif|txt|swf|mpg|mp4|avi)$ {
           expires 30d;
   }


   location / {
       rewrite ^(.*)$ /index.php?action=$1 last;
   }

   location ~ \.php$ {
           try_files $uri =404;
           fastcgi_pass unix:/tmp/php5-fpm.sock;
           fastcgi_index index.php;
           fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
           include fastcgi_params;
           fastcgi_read_timeout 600;
   }
}

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