Browsed by
Tag: WordPress

WordPress位於reverse proxy後的設定方式Ⅱ

WordPress位於reverse proxy後的設定方式Ⅱ

近期有不知名大大前來留言,才發現我的WordPress對於處理外部真實IP的部份沒有做好,雖然前一篇文章已經成功設定好nginx將real IP搞成HTTP header的一部份,但後端WordPress完全沒有拿來用呀!XD

我們需要在 wp-config.php 內取得真實IP後,再覆寫 header 資訊即可:

if ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
	$http_x_headers = explode( ',', $_SERVER['HTTP_X_FORWARDED_FOR'] );
	$_SERVER['REMOTE_ADDR'] = $http_x_headers[0];
}

WordPress位於reverse proxy後的設定方式

WordPress位於reverse proxy後的設定方式

參考文章 https://medium.com/@tyh409700530/nginx-reverse-proxy-wordpress-in-https-mode-a21658f23978 ,使用 nginx,於 nginx 設定檔設定:

# location 設定
location / {
    proxy_pass http://127.0.0.1:8080;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Host $server_name;
    proxy_set_header X-Forwarded-Proto $scheme;

    proxy_redirect off;
}

確保wp-config.php加入以下原始碼,否則使用HTTPS連線時,有機會遇到redirect loop (HTTP 302):

if (isset($_SERVER[‘HTTP_X_FORWARDED_HOST’])) {
    $_SERVER[‘HTTP_HOST’] = $_SERVER[‘HTTP_X_FORWARDED_HOST’];
}
if (isset($_SERVER[‘HTTP_X_FORWARDED_PROTO’])) {
    if ($_SERVER[‘HTTP_X_FORWARDED_PROTO’] == ‘https’) {
        $_SERVER[‘HTTPS’] = ‘on’;
    }
}

官網提供的範例是:

if( strpos( $_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false )
    $_SERVER['HTTPS'] = 'on';