如何使用nginx和php-fpm路由请求url子文件夹路径到特定的php页面



我第一次使用本地nginx服务器来建立一个我正在建设的网站,我在设置nginx配置以我想要的方式处理url请求时遇到了麻烦。我的网站提供多个php页面作为用户通过网站导航。在最初使用本地php服务器开发站点时,我使用带有window.location.href更改的GET请求进行站点导航。例如:

http://localhost:8000/shop.php?filter=all&sort=id_asc&page=3

然而,由于它将是一个小型企业的电子商务网站,我想以更干净,更专业的方式处理url。

我的网站结构是这样的:

网站:

->index.php  
->shop.php  
->about.php  
->product-page.php  
->/css/  
->/javascript/  
->/php/

我想配置nginx以以下方式路由url路径

www.mywebsite.com -> routes to index.php  
www.mywebsite.com/shop -> routes to shop.php  
www.mywebsite.com/shop/anything -> routes to shop.php  
www.mywebsite.com/about -> routes to about.php  
www.mywebsite.com/product -> routes to product-page.php   
www.mywebsite.com/product/anything -> routes to product-page.php 

在问这里之前,我在几天内尝试了许多建议,但由于这样或那样的原因,404,500内部错误和重定向循环,一切都失败了。我希望在我转移到网站的其他方面时,在这里获得一些东西,这样我就不会把头撞在墙上了。下面是我的nginx配置文件当前的状态:

server {
listen 80 ;
listen [::]:80 ;
server_name localhost;
root /var/www/html/reagansrockshop;
index index.php index.html;
location / {
try_files $uri $uri/ =404;
}
location = /shop {
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
fastcgi_index shop.php;
try_files $uri /shop.php;
}
location /shop/ {
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
try_files $uri /shop.php;
}
location ~ .php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+.php)(/.+)$;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}

}

我该如何着手解决这个问题?如果有一个更好的标准在构建一个网站和它的url,请让我知道。这是我的第一个网站,也是第一次使用nginx,所以我对最佳实践有点幼稚。

如果你需要一个php脚本来负责整个路径,你需要这样的配置:

root /var/www/html/reagansrockshop; # root directive is necessary to define where '/' is
location /shop/ { # this means "all URLs starting with '/shop/' "
index /shop.php; # be careful with path to the file here
}

虽然我更愿意推荐一个更传统和更干净的项目结构。

在项目根目录下创建两个目录:shopproduct。移动shop.phpproduct-page.php到指定的文件夹中,并重命名为index.php。这个结构的nginx配置如下:

server {
listen 80 ;
listen [::]:80 ;
server_name localhost;
root /var/www/html/reagansrockshop;
index index.php index.html;
location / {
index index.php;
try_files $uri $uri/ =404;
}
location /shop/ {
try_files $uri $uri/ /shop/index.php?$args;
}
location /product/ {
try_files $uri $uri/ /product/index.php?$args;
}
location ~ .php$ {
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}

最新更新