隐藏php文件扩展名和使用htaccess隐藏index.php

3

这个问题已经被问了无数次,但不是我想要的答案。我尝试结合不同的解决方案,但我的 .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返回到`localhost/project/´。
另外一个问题:重写规则如何影响搜索引擎。 页面(即contact.php,about-us.php等)是否仍将被索引?
额外的+1和赞扬给那些在他们的答案中详细解释了htaccess中每行/规则的作用的人。 我仍在学习.htaccess,所以每个细节都很重要且相关!
1个回答

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]

不,它在 http://localhost/project/.htaccess 中,所有其他的 .php 文件也在 http://localhost/project 中。 - Bram Vanroy
index.php 仍然重定向到 localhost/,其他链接可以正常工作! - Bram Vanroy
也许这与XAMPP有关? - Bram Vanroy
再次感谢。无法测试最后的代码,但当项目上线时我会通知您! - Bram Vanroy
当然,随时欢迎在这里留言,我会尽快回复。 - anubhava
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接