简体   繁体   English

可接受的mod_rewrite友好网址方法?

[英]acceptable mod_rewrite friendly-url approach?

I try to rewrite all url's to a single php file, unless the url leads to an existing file because existing files like images should be handled by the server directly. 我尝试将所有url重写为单个php文件,除非该URL导致存在文件,因为图像之类的现有文件应直接由服务器处理。 But if someone uses a url that looks like a file, and this file doesn't exist, it should get a 404. 但是,如果有人使用的URL看起来像文件,而该文件不存在,则应该得到404。

I came up with the following .htaccess file. 我想出了以下.htaccess文件。 Is this a valid approach? 这是有效的方法吗? It will be on a production server this friday so I would like to know for sure that there is no security risk or is a bad practice of some kind. 它将在这个星期五在生产服务器上,因此我想确定地知道没有安全风险或某种不良做法。

The first rule should make sure that any url that looks like if a file is being requested will get 404 (only if the file doesn't exist of course). 第一条规则应确保任何看起来像是在请求文件的URL都将得到404(当然,仅当文件不存在时)。

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)\.([-A-z0-9]+)$ - [R=404,L]

If above doesn't match, there is a second rule that rewrites all other non existing files to index.php (like eg /products/23). 如果以上内容不匹配,则有第二条规则将所有其他不存在的文件重写为index.php(例如/ products / 23)。 In this case index.php will handle the rest of the routes. 在这种情况下,index.php将处理其余路由。

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php [L]

If no rule mathes, it means it is an existing file is found and will be served by apache directly, like existing images and scripts. 如果没有规则,则表示它是一个现有文件,将由apache直接提供,就像现有的图像和脚本一样。

Is this a valid approach? 这是有效的方法吗? Thanks. 谢谢。

EDIT: 编辑:

a slightly shorter approach with similar result: 一种稍短的方法,结果类似:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)\.([-A-z0-9]+)$ - [R=404,L]

FallbackResource /index.php

Seems to work. 似乎可以工作。

I would only do your second check (if file exists) and if not, always redirect to your index.php. 我只会做第二次检查(如果文件存在),否则,请始终重定向到您的index.php。

There you can do your checks for product etc. and use 在那里您可以检查产品等并使用

header('HTTP/1.0 404 Not Found');
include('404.html');                  // <----- this is your 404 file
exit();

if you want to generate a 404 error. 如果要生成404错误。

Here is how I do it in my .htaccess file 这是我在.htaccess文件中执行的操作

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1

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

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