
我正在開發一個網站來顯示不同的產品,用戶可以透過「mydomain.com/product/1.html」、「mydomain.com/product/2.html」等網址存取不同的產品頁面
但我不想直接呈現這些靜態 html 文件,而是先在 mydomain.com/product.php 載入一個 php 腳本
所以我想將 'mydomain.com/product/1.html' 重定向到 'mydomain.com/product.php' 但不要更改其原始網址
我嘗試了alias、try_files、return,但它們都將url重寫為“mydomain.com/product.php”
我是 Nginx 的新手,這可能是一個非常簡單的問題,但我已經嘗試了幾天來實現這一點。
答案1
有很多方法可以做到...
最簡單的是
rewrite ^/product/ /product.php;
在伺服器情境.您的原始請求 URI(即/product/1.html
)將可作為數組項值用於product.php
腳本。$_SERVER['REQUEST_URI']
您也可以rewrite
在以下位置使用指令地點上下文,這可能會稍微(非常稍微)性能更高:
location /product/ {
rewrite ^ /product.php last;
}
如果需要,您可以取得產品程式碼並將其product.php
作為查詢參數傳遞給腳本:
rewrite ^/product/(.*)\.html$ /product.php?product=$1;
或者
location /product/ {
rewrite ^/product/(.*)\.html$ /product.php?product=$1 last;
}
這樣,您的產品代碼(1
對於/product/1.html
URI、2
對於/product/2.html
URI 等)將可作為數組項值用於product.php
腳本。$_GET['product']
您甚至可以為此定義一個單獨的 FastCGI 處理程序:
location /product/ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root/product.php;
fastcgi_pass <fastcgi_upstream_or_socket>;
}
(原始請求 URI 將透過 提供$_SERVER['REQUEST_URI']
),或者如果您希望透過以下方式提供產品代碼$_GET['product']
:
location ~ /product/(.*)\.html$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root/product.php;
fastcgi_param QUERY_STRING product=$1;
fastcgi_pass <fastcgi_upstream_or_socket>;
}