简体   繁体   English

如何使用 htaccess 隐藏 php 文件扩展名?

[英]How can I hide php file extension using htaccess?

RewriteRule ^site/index$ site/index.php [NC,L]

this line does hide the extension successfully.此行确实成功隐藏了扩展名。 Now I do not want the page with the extension to be accessible;现在我不想访问带有扩展名的页面; if one tries to access that page with the extension, it must show an error.如果尝试使用扩展名访问该页面,则必须显示错误。 Only the one that has the extension hidden that must be accessible.只有具有隐藏扩展名且必须可访问的扩展名。

it must show an error.它必须显示错误。

To return a 403 Forbidden when accessing /site/index.php you could do the following before the existing rewrite:要在访问/site/index.php时返回 403 Forbidden,您可以在现有重写之前执行以下操作:

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^site/index\.php$ - [F]

The condition that checks against the REDIRECT_STATUS is necessary in order to prevent the rewritten URL also triggering a 403.检查REDIRECT_STATUS的条件是必要的,以防止重写的 URL 也触发 403。

However, it would be more SEO-friendly to redirect/correct such requests instead.但是,改为重定向/更正此类请求对 SEO 更友好。

Aside:在旁边:

this line does hide the extension successfully.此行确实成功隐藏了扩展名。

Just wording I guess, but "this line" doesn't "hide" anything.我猜只是措辞,但“这条线”并没有“隐藏”任何东西。 It specifically adds the extension back.它专门添加了扩展名。 (The extension is already hidden in the initial request.) (扩展名已经隐藏在初始请求中。)

@MrWhite gave an answer that showed how to throw an error message like you asked, but why would you want to throw an error message instead of just redirecting example.com/page.php to example.com/page ? @MrWhite 给出了一个答案,显示了如何按照您的要求抛出错误消息,但是为什么您要抛出错误消息而不是仅仅将example.com/page.php重定向到example.com/page Here is the .htaccess code for that:这是 .htaccess 代码:

RewriteEngine on
RewriteRule ^(.+)\.php$ /$1 [R,L]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ /$1.php [NC,END]

This makes sure that both /page and /page.php go to the same url ( /page ) and serve the same page/file ( /page.php ) This makes sure that both /page and /page.php go to the same url ( /page ) and serve the same page/file ( /page.php )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM