htaccess选择任何网址

时间:2012-02-21 09:56:53

标签: php regex .htaccess mod-rewrite

我想将尝试访问文件夹中文件的所有网址重定向到我记录下载文件的常见php页面,并检查用户是否登录,我正在尝试以下方式,但我没有得到必要的结果

方法1:

RewriteEngine on
RewrteRule ^(.+)$ index.php?file=$1

方法2:

RewriteEngine on
RewriteRule ^([a-zA-Z0-9\-]+)$ index.php?file=$1

我的index.php

<php echo 'file - ' . $_REQUEST['file']; ?>

当我将网址用作http://localhost/next/files/Cool时 输出方法1:

file - index.php 

输出方法2:

file - Cool 

你能否告诉我,我在方法1中做了什么错。 我可以使用Method-2,但fileName可以是任何[可以包含所有字符],所以我需要一个涵盖所有的正则表达式[如在Method-1中]

此致

3 个答案:

答案 0 :(得分:1)

RewriteEngine on
RewriteRule ^(.*)$ index.php?file=$1 [NC,L]

答案 1 :(得分:1)

方法1的问题在于您创建了无限重定向。 由于所有文件都被重定向到index.php,index.php本身也会重定向到index.php,依此类推。

您必须从重定向中明确排除index.php:

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/index.php
RewriteRule ^(.+)$ /index.php?file=$1

答案 2 :(得分:1)

写下你的第一条规则:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-f
# forward requests to index.php as a query parameter
RewriteRule ^(.*)$ index.php?file=$1 [QSA,L]

在index.php中,将file查询参数读为:

echo 'file - ' . $_GET['file'];