php - 如何使用 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 conf此时的状态:
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
}
虽然我宁愿推荐一个更传统、更干净的项目结构。
在您的项目根目录中创建两个目录:shop
和product
. 移动shop.php
并product-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;
}
推荐阅读
- amazon-web-services - Amazon CloudWatch Insights 查询
- python - 重复直到完成
- video - ffmpeg 段复用器:重新加入段以取回输入视频
- user-interface - 什么 UI 框架使用 VS-Code?(Visual Studio 代码)
- components - 在 SAP Commerce / Hybris 的 Backoffice 中查找组件的名称
- react-native - 将 .tflite(model) 和 .txt(labels) 导入 React Native 项目
- unity3d - Unity 中如何计算变换的说明
- java - 如何使用 MySQL 请求生成实体类?
- java - 等待线程完成 .join 不一致
- prometheus - 如何可视化所有请求的平均响应时间