繁体   English   中英

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

[英]How to route request url subfolder paths to specific php pages using nginx and php-fpm

我第一次使用本地 nginx 服务器来设置我正在构建的网站,但我在设置 nginx 配置以处理 Z572D4E421E5E6B9BC11D815E8A02711 方式时遇到了麻烦。 当用户浏览网站时,我的网站提供多个 php 页面。 最初使用本地 php 服务器开发站点时,我使用 GET 请求和 window.location.href 更改以进行站点导航。 例如:

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 conf 的 state :

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM