如何加载 nextjs 路由以及在 nginx 服务器上运行的 php 驱动网站?

问题描述 投票:0回答:1

我尝试在 ubuntu 系统上创建一个 php 驱动的网站以及 nextjs 网站。我已经尝试过以下方法。

假设我有一个用 php 构建的网站,比如 mysite.com,有 2 个页面 mysite.com/ & mysite.com/about.php

同时,我有一个 nextjs 网站在端口 3000 上运行,网址为 127.0.0.1:3000 ,还有一个页面 127.0.0.1:3000/blog

我需要的是在 URL mysite.com/blog 上加载 nginx 博客页面。 nextjs 还会提供更多内容

通过参考一些文章,我在nginx中尝试了以下设置,但无法工作

server {
    listen 80;
        listen [::]:80;

        root /var/www/nginx/mysite;
        index index.html index.htm index.nginx-debian.html;

        server_name mysite.com www.mysite.com;

        location / {
                try_files $uri $uri/ =404;
        }

        location ~ \.php$ {
        #try_files $uri =404;
        #include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php7.4-fpm.sock;
        include fastcgi_params;
    }

    location /blog {
           proxy_pass          http://127.0.0.1:3000;
        }

}

下面列出了观察结果和问题

  • mysite.com/index.html 工作正常
  • mysite.com/about.php 未加载,而是下载 php 文件
  • mysite.com/blog 从 nextjs 加载,我可以在源代码上看到,但无法正确加载资源
php nginx next.js reverse-proxy virtualhost
1个回答
0
投票

我可以通过添加以下内容来解决该问题。

server {
    listen 80;
    server_name mysite.com www.mysite.com;

    access_log /var/www/nginx/mysite/logs/access.log;
    error_log  /var/www/nginx/mysite/logs/error.log error;

    root /var/www/nginx/mysite;
    index index.php index.html;

    location /blog {
        proxy_pass          http://127.0.0.1:3000;
    }

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php {
        fastcgi_index index.php;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;

        include fastcgi_params;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    # Prevents caching of css/less/js/images, only use this in development
    location ~* \.(css|less|js|jpg|png|gif)$ {
        add_header Cache-Control "no-cache, no-store, must-revalidate"; 
        add_header Pragma "no-cache";
        expires 0;
    }

    
}

我看到的一个小问题是,虽然博客从 nextjs 加载,但它仍然在控制台中显示 404,我想我错过了下面代码片段中的一些内容

location /blog {
    proxy_pass          http://127.0.0.1:3000;
}

location / {
    try_files $uri $uri/ /index.php?$query_string;
}

此外,以博客(donatetest.com/blogedxx)开头的内容也会路由到 nextjs,这不应该发生

针对问题添加了屏幕截图

© www.soinside.com 2019 - 2024. All rights reserved.