[英]Nginx redirect all requests from subdirectory to another subdirectory root
我對Nginx很新,所以請耐心等待。
我正在嘗試將所有請求從一個子目錄(存儲)重定向到另一個子目錄(交易)的根目錄。 請參閱下面的進度。 目標子目錄(交易)中的站點是一個magento站點,因此這是當前大多數規則的用途。
server {
server_name example.com *.example.com;
root /usr/share/nginx/html/example.com/public_html;
index index.php index.html index.htm;
access_log /var/log/nginx/example.access.log;
error_log /var/log/nginx/example.error.log;
location / {
try_files $uri $uri/ /index.html;
}
location /trade/ {
index index.html index.php;
try_files $uri $uri/ @handler;
expires 30d;
}
location ~ /store {
rewrite /trade permanent;
}
location ~ ^/trade/(app|includes|lib|media/downloadable|pkginfo|report/config.xml|var)/ { internal; }
location /trade/var/export/ { internal; }
location /. { return 404; }
location @handler { rewrite / /trade/index.php; }
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
我用來重定向的部分如下:
location ~ /store {
rewrite /trade permanent;
}
這適用於example.com/store,但不適用於example / store / index.php或任何其他帶有args的uri。 我有一種感覺,底部的php文件部分覆蓋了處理。 這就是為什么我把〜放在商店位置的前面,因為這里的文檔聲明這將首先處理。 處理是停止還是繼續?
我已經閱讀了關於嵌套php規則的內容,但我試過這個無濟於事。
我非常感謝任何幫助。
好吧嘗試這樣的事情
location ^~ /store(.*) {
return 301 $scheme://$http_host/trade$1$is_args$query_string;
}
試圖盡可能避免使用硬編碼的東西並使用return,因為它優先於永久性重寫
好,
回到這一點,我可以看到這個問題。
在Nginx中使用〜前置位置指令時,這意味着您要在指令中處理正則表達式(區分大小寫,〜*表示不區分大小寫)。 我相信所有正則表達式指令都會先於其他任何指令處理,但我有待糾正。
所以當我使用時:
location ~/store {
rewrite /trade permanent;
}
那里沒有正則表達式。 它只是匹配/存儲和重定向到交易。
經過一番調查(並對我的正則表達式進行了拋光,這是垃圾),我回過頭來想出一個有效的解決方案。
location ~ ^/store/(.*) {
rewrite ^/store(.*) /trade permanent;
}
在這里,我要求指令通過輸入〜然后將任何url與/ store /匹配來處理正則表達式。
然后,根據文檔,重寫語法是:
重寫正則表達式替換[flag]
所以我將所有url與store中的store匹配,並永久地將它們重定向到新的子文件夾。
真的很容易,實際上很尷尬,但是嘿,每天都是上學日。 我願意糾正所有這些並希望它可以幫助某人。
您需要確保您的location ~ \\.php$
handler不會在舊文件夾下面使用任何URL。 實際上,在http://nginx.org/r/location中清楚地記錄了優先級規則,您可以使用正則表達式,或者更好的是,使用與^~
修飾符的基於前綴的匹配來指示搜索必須停止不試圖看看基於正則表達式的\\.php$
location
是否匹配:
location ^~ /old/long/path/ { # will match /old/long/path/index.php, too
rewrite ^/old/long/path/(.*)$ /new/$1 permanent;
}
上面的代碼段可能是最有效的方法,但這是另一種方法:
location ~ /old/long/path/(.*) {
return 301 /new/$1$is_args$args;
}
為什么一個例子有$is_args$args
而另一個沒有? 好問題! 請注意, location
指令以及rewrite
指令的第一個參數都基於$uri
變量的內容進行操作,而不是$request_uri
。 長話短說,但$uri
不包含$args
,因此,在這兩種情況下, $1
都不包含任何args
; 但是,在rewrite
的情況下,這種情況被認為是如此常見,以至於$args
會被nginx自動添加回來,除非新字符串以?
結尾?
角色,見http://nginx.org/r/rewrite 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.