简体   繁体   English

.htaccess隐藏.PHP并重写URL

[英].htaccess hide .PHP and rewrite URL

I've set up a .htaccess file to rewrite the url example.com/foo too example.com/foo.php I can separately get the URL to redirect to error.php if it ends in .php, but I can't seem to do both together. 我已经设置了一个.htaccess文件来重写URL example.com/foo example.com/foo.php如果它以.php结尾,我可以分别获取URL重定向到error.php ,但是我不能似乎两者都在一起。

I've seen other sites hide .php and I want to understand how to do that. 我看到其他网站隐藏了.php,我想了解如何做到这一点。

Here's what I've tried: 这是我尝试过的:

//.htaccess file

RewriteEngine On    # Turn on the rewriting engine
RewriteRule    ^([A-Za-z0-9-_]+)/?$    $1.php    [NC,L]
RewriteRule    ^([A-Za-z0-9-_]+).php?$    error.php    [NC,L]

NOTES 笔记

Here is what worked for me. 这对我有用。 I'm going to leave it hear for reference as I'm not sure it all necessarily is necessary. 我不确定它是否一定有必要供大家参考。

    RewriteEngine On

    RewriteRule (.*)index$ http://%{HTTP_HOST}/error [R=404]
    RewriteCond %{THE_REQUEST} ^\w+\ /(.*)\.php(\?.*)?\ HTTP/
    RewriteRule ^ http://%{HTTP_HOST}/error [R=301]
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule .* $0.php
    ErrorDocument 404 /error.php 
    ErrorDocument 301 /error.php 

Considering your comment to your own question it seems this is what you are looking for: If the request targets something to what a php script exist with the same name but an added .php file name extension, then internally rewrite to that. 考虑到您对自己的问题的评论,这似乎是您正在寻找的内容:如果请求将某对象定位到具有相同名称但添加了.php文件扩展名的php脚本,则在内部进行重写。 Rewrite to /error.php in all other cases, if the request resource does not directly exist in the file system. 如果请求资源在文件系统中不直接存在,则在所有其他情况下都重写为/error.php

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /error.php [L]

And a general hint: you should always prefer to place such rules inside the http servers host configuration instead of using dynamic configuration files (".htaccess"). 还有一个一般性提示:您应该始终喜欢将此类规则放置在http服务器主机配置中,而不是使用动态配置文件(“ .htaccess”)。 Those files are notoriously error prone, hard to debug and they really slow down the server. 众所周知,这些文件容易出错,难以调试,并且确实降低了服务器的速度。 They are only provided as a last option for situations where you do not have control over the host configuration (read: really cheap hosting service providers) or if you have an application that relies on writing its own rewrite rules (which is an obvious security nightmare). 仅当您无法控制主机配置(阅读:真正便宜的托管服务提供商)或者您的应用程序依赖于编写自己的重写规则(这显然是安全噩梦)时,才提供它们作为最后的选择。 )。

I do it using this two rules: 我使用以下两个规则来做到这一点:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

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

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