首页 > 解决方案 > ELB 在 EC2 上使用 Nginx 转移到 wordpress 显示 404

问题描述

※ 以我example.com为例

我正在使用 ELB 和 EC2 开发一个应用程序。结构如下。

当用户访问 /manage/* 时,ELB 将转移到 wordpress 托管实例。

这是ELB设置。

关于ELB它可以工作,但是转移到wordpress端后,CSS和JS文件的响应显示404。

当我访问 /magazine/* URL 时,wordpress 主题的加载动画开始工作,但由于未加载 css 和 js 而卡住。

我猜这是因为 nginx 配置但无法解决。

这是配置文件的内容。我只是添加/etc/nginx/conf.d/vhosts.conf和编写一些设置。我不碰其他文件。

# vhosts.conf
server {
    listen 80;
    server_name example.com;

    return 301 https://$host$request_uri;

}

server {
    listen 443;
    server_name example.com;

    root /var/www/html;

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

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

下面/var/www/html,项目的结构如下。

/wp-content
/wp-admin
/wp-include
index.php
wp-config.php

如需其他信息,


附加信息


结果

制作/var/www/html/magazine目录并将所有文件移动到其中。

server {
        listen 80;
        server_name example.com;

        return 301 https://$host$request_uri;

}

server {
        listen 443;
        server_name example.com;

        location ~* /(wp-config|xmlrpc)\.php {
                deny all;
        }

        location @magazine {
                rewrite ^/magazine(.*) /magazine/index.php?$args;
        }

        location ^~ /magazine {
                root /var/www/html;
                index index.php index.html index.htm;
                try_files $uri $uri/ @magazine;

                location ~ \.php$ {
                        fastcgi_split_path_info ^(.+\.php)(/.+)$;
                        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
                        fastcgi_index index.php;
                        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                        fastcgi_param PATH_INFO $fastcgi_path_info;
                        include fastcgi_params;
                }

        }

}

标签: amazon-web-servicesnginx

解决方案


由于您不是从 url 的根目录提供 wordpress,因此您必须告诉 wordpress 从子目录加载资产。wordpress 支持文章中描述了如何做到这一点。[1]

您是否检查过WP_HOMEWP_SITEURL变量是否设置正确?
您能否编辑您的问题并包含您的浏览器尝试为 css 和 js 文件加载的 URL,因为它在屏幕截图中不完全可见?

编辑:

多亏了额外的信息,我们知道 wordpress 按预期构建了路径。所以,现在我分享你的观点,即 nginx 导致了这个问题。

我环顾四周,注意到 nginx 配置可能存在两个问题:

  • 根语句可能应该在 location 块内。我不知道这是否真的有必要,但很多人都这样做。[2]
  • location 块进行前缀匹配并将前缀杂志包含到$uri变量中,如 serverfault 线程中所述。[3]
    您可以使用正则表达式去除前缀,如下所示:
location ~ ^/magazine(.*) {
    root /var/www/html;
    try_files $1 $1/ /index.php?$args;
}

注意:我不知道目录重定向$1和默认重定向是否/index.php?$args对提供 js/css 资产有意义。如果没有必要,您可能应该删除它们。

参考

[1] https://wordpress.org/support/article/chang-the-site-url/#chang-the-site-url
[2] https://serverfault.com/a/258540/531099
[3] https://serverfault.com/a/455853/531099


推荐阅读