隐藏文件扩展名并重定向到https

时间:2016-07-15 21:15:40

标签: apache .htaccess redirect mod-rewrite url-rewriting

首先,我知道有很多类似的问题。我已经阅读了我能找到的所有内容,但我在其他地方看到的解决方案似乎并不适合我。我真的希望有人能在这里给我一些见解。

我正在尝试使用Apache的.htaccess指令强制我服务器上的特定页面使用ssl。除了这些指令之外,我还使用了一些重写来屏蔽.php.html扩展名。

我创建了一个页面https-test.html。我希望该页面专门针对始终重定向,因此它使用https,以便.html被剥离,例如https://www.example.com/https-test

然而,我似乎总是以循环结束。阅读Apache文档6小时让我更接近,但我仍然遗漏了一些东西。

下面是我带注释的htaccess文件。

RewriteEngine on

# If port is insecure...
RewriteCond %{SERVER_PORT} ^80$
# And requested URI is /https-test...
RewriteCond %{REQUEST_URI} ^(.*/)https-test$ [NC]
# Then point the server to the secure url:
RewriteRule . "https://www.example.com/https-test" [L,R]


# The next few lines try matching extensionless requests to .php files
# If the requested file is not a directory... 
RewriteCond %{REQUEST_FILENAME} !-d
# And we CAN find a .php file matching that name...
RewriteCond %{REQUEST_FILENAME}\.php -f
# Then point us to that .php file and append the query string.
RewriteRule ^(.+)$ $1.php [L,QSA]


# These next few lines were added by the previous project owner
# They're supposed to redirect requests like /foo.html to /foo,
# But I suspect these might be the culprit

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)/$ /$1 [R=301,NE,L]
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^([^\.]+)$ /$1.html [NE,L]


# Next few lines are legacy SEO stuff, some pages were linked to as
# php but now are html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} .php$
RewriteRule ^(.*).php$ /$1.html [L,NE]

这就是我在htaccess中的代码。如果我在Chrome中转到http://www.example.com/https-test,我会将 www.mysite.com重定向到您太多次。

1 个答案:

答案 0 :(得分:1)

你应该只是重写一下代码。您正在尝试将这两个无扩展名文件与php和html相匹配,并且看起来并不像每个条件一样。你应该添加一个条件,以确保他们没有尝试做同样的事情。

备份您的代码,用此替换您的代码并尝试一下。在尝试之前清除所有缓存。

RewriteEngine on
# If port is insecure... redirect for a specific page
RewriteCond %{HTTPS} !^on [OR]
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^http-test/?$ https://www.example.com%{REQUEST_URI} [R=301,L]

# Next few lines are legacy SEO stuff, some pages were linked to as
# php but now are html
RewriteCond %{THE_REQUEST} ^GET\ /(.+)\.php
RewriteRule ^ /%1? [R=301,L]

# The next few lines try matching extensionless requests to .php files
# If the requested file is not a directory and php file exists
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.+)$ $1.php [L,QSA]

#remove trailing slash and is not a php file 
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php !-f
RewriteRule ^([^\.]+)/$ /$1 [R=301,NE,L]

#finally redirect extensionless URI to html
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ /$1.html [NE,L]

注意我还没有完全测试过。