【问题标题】:URL re-writing using htaccess problems使用 htaccess 重写 URL 问题
【发布时间】:2017-10-04 08:40:10
【问题描述】:

我只是第一次涉足 .htaccess URL 重写的世界,但遇到了第一道障碍。但是我确定我遗漏了一些明显的东西......:)

我的 htaccess 目前看起来像这样,这是一个从 /wordpress 运行的 Wordpress 安装,但被重新编写以显示在域的顶层:

php_value short_open_tag 1

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) wordpress/$2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ wordpress/$2 [L]
RewriteRule . index.php [L]

</IfModule>

我想添加一个重写规则以允许任何人访问: /publication-details.php?id=xxx(其中 xxx 是一个数字 至 /publications/pub-xxx/

我认为这样的事情会起作用:

RewriteRule ^publication-details.php?id=([0-9]+) /publications/pub-$1 [NC]

但我已尝试将其作为一项规则,但它不起作用 - 无论我在现有规则中的哪个位置订购它。尝试访问 /publication-details.php 只会得到 404(Apache 默认)。如果我尝试 /whatever(即 URL 中没有扩展名),我会得到 Wordpress 404。

我错过了什么?!

提前致谢。

【问题讨论】:

    标签: wordpress apache .htaccess url-rewriting


    【解决方案1】:

    编辑您的永久链接到 %postname%

    add_filter( 'rewrite_rules_array','my_insert_rewrite_rules' );
    add_action( 'wp_loaded','my_flush_rules' );
    
    function my_insert_rewrite_rules( $rules )
    {
           $newrules = array();
           $newrules['([^/]+)/publication/pub-([^/])/?$'] = add_rewrite_rule( '([^/]+)/publication/pub-([^/])?$', 'index.php?pagename=$matches[1]&pub-id=$matches[3]', 'top' );
           return $newrules + $rules;
    }        
    
    add_action( 'wp_loaded','my_flush_rules' );
    
    // flush_rules() if our rules are not yet included
    function my_flush_rules(){
        $rules = get_option( 'rewrite_rules' );
        if (! isset( $rules['([^/]+)/publication/pub-([^/])/?$'] )) {
                global $wp_rewrite;
                $wp_rewrite->flush_rules();
        }
    }
    

    【讨论】:

    • 谢谢 - 这样做比将规则直接插入 htacces 有什么好处吗?
    【解决方案2】:

    RewriteRule 仅适用于 URI,不适用于查询字符串。

    要做你想做的事,你需要一个 RewriteCond (=Condition) 来检查查询字符串,例如

    RewriteCond %{QUERY_STRING} id=([0-9]+)
    RewriteRule ^publication-details.php /publications/pub-%1? [R=302,L]
    

    RewriteCond 是以下 RewriteRule 的条件。请注意,使用条件中的匹配项是规则中的 %1,而不是 $1($1 仅用于规则中的匹配项)。我在末尾添加了一个单引号来禁用查询字符串的添加,否则它将重定向到 /publications/pub-12345?id=12345。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多