隐藏php文件的扩展名并用htaccess隐藏index.php

时间:2014-12-14 11:11:34

标签: php apache .htaccess mod-rewrite

这已被问了一千次,但不是我想要的。我尝试过组合不同的解决方案,但我的.htaccess似乎并没有按照预期的那样做。

# Not sure what this does?
Options +FollowSymLinks -MultiViews

# Turn mod_rewrite on
RewriteEngine On

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]

# Redirect index in any directory to root of that directory
RewriteCond %{THE_REQUEST} ^[A-Z](3,9)\ /([^/]+/)*index\.[^\ ]*\ HTTP/
RewriteRule ^(([^/]+/)*)index(\.[a-z0-9]+)?$ http://www.example.com/$1? [R=301,L] 

现在我的网页正确地从domain.com/page1.php更改为domain.com/page1,但domain.com/index.php出现了问题。

我在本地进行测试,当转到localhost/project时,一切正常(index.php打开,但您没有在网址中看到)但是当您明确导航到{{1}时你返回到根,即localhost/project/index.php(母鸡返回localhost)。当然,这不是我想要的。我希望http://localhost/xampp/splash.php返回`localhost / project /'。

另一个问题是:重写规则如何影响搜索引擎。页面(即contact.php,about-us.php等)是否仍会被编入索引?

为他或她提供额外+1和荣誉,他们详细分析了答案中htaccess中每条线/规则的作用。我还在学习.htaccess,所以每一个细节都很重要,对我来说很重要!

1 个答案:

答案 0 :(得分:0)

此代码中的很多评论似乎都是我的:)

无论如何,您可以使用此代码来解决您的问题:

# Turn mod_rewrite on
RewriteEngine On
RewriteBase /project/

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} \s/+project/+(.*?/)?(?:index)?(.*?)\.php[\s?] [NC]
RewriteRule ^ %1%2 [R=302,L,NE]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/project/$1\.php -f [NC]
RewriteRule ^(.+?)/?$ $1.php [L]

更新:在DocumentRoot中使用

# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} \s/+(.*?/)?(?:index)?(.*?)\.php[\s?] [NC]
RewriteRule ^ %1%2 [R=302,L,NE]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [NC]
RewriteRule ^(.+?)/?$ $1.php [L]