简体   繁体   中英

$_SERVER['SERVER_NAME'] and $_SERVER['HTTP_HOST'] both different than actual URL

When accessing the URL www.domain.com/test.php , both $_SERVER['SERVER_NAME'] and $_SERVER['HTTP_HOST'] output the domain name without the www. prefix: domain.com

Why would that be this way ?

EDIT: as stated here , $_SERVER['SERVER_NAME'] could be different than the actual requested URL, however $_SERVER['HTTP_HOST'] should return the domain.

PHP version: 7.1 Apache version : 2.2

.htaccess content is as follow (the interesting part is the top rewrite block)

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
</IfModule>

# BEGIN Force SSL for SAKURA
# RewriteしてもHTTPS環境変数を有効にする
SetEnvIf REDIRECT_HTTPS (.*) HTTPS=$1


# 常時HTTPS化(HTTPSが無効な場合リダイレクト)
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{ENV:HTTPS} !on
RewriteCond %{REQUEST_URI} !/wp-cron\.php$
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>
# END Force SSL for SAKURA

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

And here is the content of test.php:

<?php 
echo $_SERVER['SERVER_NAME'];

echo  $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

Output is "domain.com" and "domain.com/test".

Well that top interesting rewrite block you mentioned is removing the www. from the URL with a 301 redirect. So there's no way of a request getting to your PHP script with the www. intact, because any request including the www. is issued a 301 redirect and never gets to the PHP script. The browser is then re-issuing the request based on the 301 redirect, and now it gets to your script without the www. .

You can test this by commenting out that top block, clearing your browser cache (important - or using a different browser), and visiting the test page again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM