【问题标题】:custom .htaccess rewrite rules自定义 .htaccess 重写规则
【发布时间】:2012-01-09 02:01:47
【问题描述】:

我想将所有内容重定向到一个脚本,例如index.php?url=inputurl

使用 if/else 我想解析 url

在 index.php 中对我的自定义表中的 url 运行查询

  • 如果 url 是马赫:echo "ok"
  • 否则什么都不做

我应该如何在Wordpress的根文件夹中设置.htaccess?

例子:

custom_table 中的 URL:

  • asd
  • dfg
  • ghj

如果用户放置:

www.mysite.com/asd

-> mod_rewrite 应该输出这个:www.mysite.com/index.php?url=asd

否则如果用户输入:

www.mysite.com/zzz

->什么都不做

【问题讨论】:

    标签: php wordpress .htaccess mod-rewrite


    【解决方案1】:

    我认为以下 .htaccess 应该可以解决问题:

    RewriteEngine On
    
    # Redirects everything that is not index.php to index.php
    RewriteCond $1 !^index\.php
    RewriteRule ^(.*)$ index.php?url=$1 [L,R]
    

    编辑:要在重写时不包括您的文件夹和文件(如 /js、/css 等),请在 RewriteRule 行之前添加以下行(请参阅 cmets):

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    

    在 PHP 脚本中:

    $url = $_GET['url'];
    
    // the method is_valid should check if the page exists in DB
    if (is_valid($url)) {
        // do something here
        // maybe redirect with header('Location: path')
    } else {
        // show a not found page (error 404)
    }
    

    【讨论】:

    • 可能他还需要RewriteCond 来检查 URL 是否引用磁盘上的实际文件,因为他很可能不希望 image/css/javascript 文件通过 @987654326 @。这个RewriteCond 会使你已经过时的那个。
    • @abhi 当然,我没有考虑过。在 RewriteRule 之前添加这两行应该可以解决这个问题,对吗? RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-d
    【解决方案2】:

    您希望既能从数据库中读取数据,又希望在不匹配的情况下什么也不做。

    这需要您运行代码来访问数据库,然后返回到 apache 进行处理,并且无法从 .htacccess(尽管它来自 httpd.conf)。

    .htaccess 解决方案是指定所有内联的“表”条目,如下所示。

    RewriteEngine on
    RewriteBase /
    
    #if asd or dfg or ghj
    RewriteCond %{REQUEST_URI} ^/(asd|dfg|ghj) [NC]
    RewriteRule . index.php?url=%{REQUEST_URI} [L]
    

    【讨论】: