如何解决如何使用 nginx 和 php-fpm
我第一次使用本地 nginx 服务器来设置我正在构建的网站,但在设置 nginx 配置以按照我想要的方式处理 url 请求时遇到问题。当用户浏览网站时,我的网站提供多个 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 的状态:
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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。