Ubuntu

Apache重寫/重定向問題

  • March 26, 2019

我的 000-default.conf 文件(Ubuntu 和 Apache 2.4.34)中有以下內容,但是當我訪問 www.mydomain.us 或 mydomain.us 時,我沒有被重定向到確實可以直接使用https的 https 頁面://www.mydomain.us

<VirtualHost *:80>
       # The ServerName directive sets the request scheme, hostname and port that
       # the server uses to identify itself. This is used when creating
       # redirection URLs. In the context of virtual hosts, the ServerName
       # specifies what hostname must appear in the request's Host: header to
       # match this virtual host. For the default virtual host (this file) this
       # value is not decisive as it is used as a last resort host regardless.
       # However, you must set it for any further virtual host explicitly.
       #ServerName www.example.com

       ServerAdmin webmaster@localhost
       DocumentRoot /var/www/html

       # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
       # error, crit, alert, emerg.
       # It is also possible to configure the loglevel for particular
       # modules, e.g.
       #LogLevel info ssl:warn

       ErrorLog ${APACHE_LOG_DIR}/error.log
       CustomLog ${APACHE_LOG_DIR}/access.log combined

       # For most configuration files from conf-available/, which are
       # enabled or disabled at a global level, it is possible to
       # include a line for only one particular virtual host. For example the
       # following line enables the CGI configuration for this host only
       # after it has been globally disabled with "a2disconf".
       #Include conf-available/serve-cgi-bin.conf
RewriteEngine on
RewriteCond %{SERVER_NAME} =*.mydomain.us
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

我在錯誤日誌中沒有任何內容,並且訪問日誌顯示,正如所呈現但未預期的那樣,它在 /var/www/html 中提供頁面。我用Google搜尋但沒有找到任何與此問題匹配的有用資訊。

提前致謝。

RewriteCond %{SERVER_NAME} =*.mydomain.us

這個條件永遠不會匹配,所以重定向永遠不會發生。CondPattern上的=前綴使其成為字典字元串比較,因此它試圖將變數(預設情況下請求的主機名)與文字 string 匹配。SERVER_NAME``*.mydomain.us

您將需要類似以下的內容:

RewriteEngine on
RewriteCond %{HTTP_HOST} \.example\.com
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [END,NE,R=permanent]

HTTP_HOST伺服器變數始終包含Host:請求標頭的值。預設情況下,SERVER_NAME也包含相同的值,但是,根據UseCanonicalName指令的值,此變數可以包含ServerName指令中使用的值,而不是請求中的值。


但是,您不一定需要 mod_rewrite ,一個簡單的 mod_aliasRedirect可能就足夠了:

Redirect 301 / https://www.example.com/

如果您有多個主機,則為每個主機配置一個單獨的 vHost。

引用自:https://serverfault.com/questions/960103