【问题标题】:Configuring php with nginx inside a reactjs app在 reactjs 应用程序中使用 nginx 配置 php
【发布时间】:2018-04-06 19:53:09
【问题描述】:

我有一个反应应用程序的 nginx 配置。不过,我还想包含一个我用 php 动态构建的 sitemap.php。

这是我的 nginx 配置:

server {
    listen 80;
    listen [::]:80;
    server_name mysite.com;

    index index.html index.htm;


    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    }


    location /sitemap.xml {
        alias /var/www/web-app/public/sitemap.php;
    }


    location / {
        root /var/www/web-app/public;
        try_files $uri $uri/ /index.html;
        default_type "text/html";
    }

}

sn-ps 文件由以下内容组成:

# regex to split $uri to $fastcgi_script_name and $fastcgi_path
fastcgi_split_path_info ^(.+\.php)(/.+)$;

# Check that the PHP script exists before passing it
try_files $fastcgi_script_name =404;

# Bypass the fact that try_files resets $fastcgi_path_info
# see: http://trac.nginx.org/nginx/ticket/321
set $path_info $fastcgi_path_info;
fastcgi_param PATH_INFO $path_info;

fastcgi_index index.php;
include fastcgi.conf;

此外,它托管在 Ubuntu 16.04 digitalocean VPS 上。

我的 react 应用仍然可以正常加载。它基于我的站点根目录 (/var/www/web-app/public) 中的 index.html。如果我将 test.php 放在公用文件夹中,则会收到 404 错误。对于我的 sitemap.xml 别名,它会正确转发到 sitemap.php(也是公开的),但 php 不会呈现。

所以我最大的两个问题是: 1. 为什么我在 /mysite.com/test.php 上收到 404? 2. 为什么我的 php 运行时没有渲染? (即sitemap.php)

【问题讨论】:

    标签: php nginx ubuntu-16.04 digital-ocean


    【解决方案1】:

    您的location ~ \.php$ 块缺少root 语句,因此将找不到您的PHP 文件。由于这似乎是一个常见的 rootlocation / 块,只需将语句向上移动到 server 块范围:

    root /var/www/web-app/public;
    
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    }
    
    location / {
        try_files $uri $uri/ /index.html;
        default_type "text/html";
    }
    

    有多种方法可以将/sitemap.xml 重定向到/sitemap.php,但rewrite...last 是最简单的并且对用户不可见:

    location = /sitemap.xml {
        rewrite ^ /sitemap.php last;
    }
    

    请参阅this document 了解location 语法,以及this one 了解rewrite 指令。

    【讨论】:

    • 谢谢。这回答了这两个问题,你给了我关于如何正确重写的额外信息。
    猜你喜欢
    • 1970-01-01
    • 2020-02-14
    • 2019-07-18
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多