隐藏 php 文件的扩展名并隐藏索引.php使用 htaccess


Hide extension of php files and hide index.php with htaccess

这已经被问了一千次了,但并不完全是我想要的。我尝试组合不同的解决方案,但我的 .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打开,但您在 url 中看不到(,但是当您显式导航到localhost/project/index.php时,您将返回到根目录,即 localhost(母鸡回到http://localhost/xampp/splash.php(。当然,这不是我想要的。我希望localhost/project/index.php返回到"本地主机/项目/"。

不过,还有一个问题:重写规则如何影响搜索引擎。页面(即联系人.php、关于我们.php等(是否仍会被编入索引?

额外的+1和对他或她的赞誉,他或她在答案中详细细分了htaccess中的每一行/规则的作用。我还在学习.htaccess,所以每个细节都很重要,与我相关!

有问题的这段代码中的很多注释似乎是我:)

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

# 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]