背景

许多网站出于SEO内链的需要,都会设置blog栏目。今天来说一下如何使用 nginxproxy_passwordpress 固定到 网站的 /blog 栏目下。

思路

将 wordpress 部署在本地的一个端口,然后在站点 nginx 的 server 配置中,将 blog 通过 proxy_pass 转到本地端口的wordpress实例上。这样我们通过 yoursite.com/blog 就可以访问到 wordpress 的首页了。

具体的配置如下:

nginx配置

使用一个本地端口监听 wordpress

server {
    listen 7080;
    server_name _;

    root /usr/share/nginx/wordpress; # 网站目录
    index index.html index.htm index.php;

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

    location ~ \.php$ {
        try_files $uri =404;

        include fastcgi.conf;
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock; # 视情况而定
    }
}

在网站的 server 块中增加如下部分

location ^~ /blog/ {
    proxy_pass http://127.0.0.1:7080/;
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Proto $scheme;
}

wordpress 配置,在 wp-config.php 里面添加如下代码,这部分代码主要是处理 https 的问题,以及处理wp-admin的访问路径:

/** set the site URL */
define('WP_HOME','/blog');
define('WP_SITEURL','/blog');

/* SSL Settings */
define('FORCE_SSL_ADMIN', true);

/* Turn HTTPS 'on' if HTTP_X_FORWARDED_PROTO matches 'https' */
if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false) {
    $_SERVER['HTTPS'] = 'on';
}

if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {
    $_SERVER['HTTP_HOST'] = $_SERVER['HTTP_X_FORWARDED_HOST'];
}

$_SERVER['REQUEST_URI'] = "/blog".$_SERVER['REQUEST_URI'];

注意,上面的代码一定要加载 require_once( ABSPATH . 'wp-settings.php' );之前,否则可能会出现 wp-admin 页面的 403 错误。

更新 & 补充

参照上面的部署之后,评论者的IP都是 127.0.0.1。这个不能容忍,需要做如下配置:

Nginx:


location ^~ /blog/ { proxy_pass http://127.0.0.1:7080/; # 增加一行 proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Proto $scheme; }

wp-config.php


/* Turn HTTPS 'on' if HTTP_X_FORWARDED_PROTO matches 'https' */ if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false) { $_SERVER['HTTPS'] = 'on'; } // 增加这样一段代码 if (isset($_SERVER['HTTP_X_REAL_IP'])) { $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_X_REAL_IP']; } if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) { $_SERVER['HTTP_HOST'] = $_SERVER['HTTP_X_FORWARDED_HOST']; }

重启 Nginx 即可。

参考链接