在 reactjs 应用程序中使用 nginx 配置 php

Configuring php with nginx inside a reactjs app

我有一个用于 React 应用程序的 nginx 配置。但是,我还想包括一个 sitemap.php,我用 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";
    }

}

片段文件包含以下内容:

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

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

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

有关 rewrite 指令,请参见 this document for location syntax, and this one