2016-11-29 61 views
1

我遇到了一個我無法解釋也不正確的奇怪行爲。我需要將每個HTTP請求重定向到HTTPS。我使用下面的代碼:RewriteRule更改URL而不是映射到文件

RewriteEngine On 
RewriteBase/

RewriteCond %{HTTPS} off 
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L] 

RewriteRule ^index\.php$ - [L] 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
# The query string in the rewrite is for testing purposes 
RewriteRule (.*) /index.php?url=$1&%{REQUEST_URI}&http=%{HTTPS} [L] 

到目前爲止,它的工作原理。然後,我需要一個頁面是HTTP,所以我加了一些重寫條件:

RewriteEngine On 
RewriteBase/
RewriteCond %{HTTPS} on 
RewriteCond %{REQUEST_URI} ^/not-https 
RewriteRule .* http://%{HTTP_HOST}%{REQUEST_URI} [R=302,L] 

RewriteCond %{HTTPS} off 
RewriteCond %{REQUEST_URI} !^/not-https 
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L] 

RewriteRule ^index\.php$ - [L] 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule (.*) /index.php?url=$1&%{REQUEST_URI}&https=%{HTTPS} [L] 

現在,這裏發生了什麼。由於某些原因,當訪問/not-https頁面時,它將重定向到/index.php?url=not-https&/not-https&https=off

以下是GET請求的映射,後跟重定向/顯示的URL。

GET: http://example.com/test 
    -> https://example.com/test with proper $_GET 

GET: http://example.com/test.jpg 
    -> https://example.com/test.jpg with no $_GET (file exists) 

GET: https://example.com/not-https 
    -> http://example.com/not-https 
    -> http://example.com/index.php?url=not-https&/not-https&https=off 

我的問題是,爲什麼在not-https變化所顯示的URL(和爲此,弄亂我的應用程序)?

回答

1

這是因爲REQUEST_URI變量的值在/index.php?...更改爲/index.php?...,使條件!^/non-https在第二條規則中成功並使其執行該規則。

更改您的第一條規則這樣:

RewriteCond %{HTTPS} on 
RewriteCond %{THE_REQUEST} \s/+not-https [NC] 
RewriteRule^http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE] 

RewriteCond %{HTTPS} off 
RewriteCond %{THE_REQUEST} !\s/+not-https [NC] 
RewriteRule^https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE] 

不像REQUEST_URI變量THE_REQUEST不改變它的其他內部重寫執行後的值。

+1

非常感謝你,解決了一切。我的猜測是'REQUEST_URI'在某種程度上發生了變化,但我在文檔中找不到任何東西。另外,我覺得很難調試'.htaccess'文件... –