【问题标题】:htaccess select any urlhtaccess 选择任何网址
【发布时间】:2012-02-21 09:56:53
【问题描述】:

我想将所有试图访问文件夹中文件的 url 重定向到一个公共 php 页面,在该页面中记录正在下载的文件并检查用户是否登录,我正在尝试以下方式,但我'没有得到所需的结果

方法一:

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

方法二:

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

我的 index.php

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

当我将 URL 用作 http://localhost/next/files/Cool 时 输出方法一:

file - index.php 

输出方法二:

file - Cool 

你能告诉我我在方法 1 中做错了什么吗? 我可以使用 Method-2,但文件名可以是任何东西[可以包含所有字符],所以我需要一个涵盖所有内容的正则表达式 [就像在 Method-1 中一样]

问候

【问题讨论】:

    标签: php regex .htaccess mod-rewrite


    【解决方案1】:
    RewriteEngine on
    RewriteRule ^(.*)$ index.php?file=$1 [NC,L]
    

    【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      这样写你的第一条规则:

      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'];
      

      【讨论】:

      • 这显然行不通,因为重写应该专门将 existing 文件也重写为 index.php。
      • 谢谢,文件名包含空格是什么小问题。说图片 (1).jpg 然后它只匹配图片(离开 (1).jpg) - 任何建议都在这里。
      • @apfelbox 请开始阅读有关 mod_rewrite 的信息,RewriteCond %{REQUEST_FILENAME} !-f 将跳过任何物理文件的重写规则。我的回答中也有 cmets,但可能您没有注意它们。
      • @user237865:如果您单击链接或在浏览器中输入http://localhost/picture (1).jpg,它将自动变为http://localhost/picture%20(1).jpg。然后在这种情况下,如果您在代码中执行$_GET['file'],您将得到picture (1).jpg
      • @anubhava 我已经知道 mod_rewrite。据我所知,问题所有者的请求是,他想将 URL 重写为 existing 文件,以便在 PHP 中进行一些预处理。这在您的解决方案中不可能,请参阅我上面的评论。
      猜你喜欢
      • 1970-01-01
      • 2014-07-30
      • 2012-09-15
      • 2014-06-12
      • 2011-11-16
      • 2017-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多