【问题标题】:Rewrite URL to remove query string重写 URL 以删除查询字符串
【发布时间】:2017-12-21 18:20:27
【问题描述】:

我有一个需要重新格式化的 URL。 example.com/?article_category=lifestyle 我希望将其格式化为:example.com/lifestyle。但是,当我尝试使用 .htaccess 文件重新格式化它时,它不起作用。我的 .htaccess 文件与我的文件位于同一目录中。文件名为 index.php。

这是我提出的重写规则:

RewriteRule ^([\w-]+)/?$ index.php?article_category=$1 [QSA,L]

我不知道为什么这不起作用。我做错了什么?

【问题讨论】:

    标签: .htaccess mod-rewrite


    【解决方案1】:

    有用的文档:RewriteCond Directive & RewriteRule Directive

    RewriteCond %{QUERY_STRING} article_category=([a-z]+)
    RewriteRule ^/?$ /%1? [R=301,L]
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([a-z]+) index.php?article_category=$1 [QSA,L]
    

    第 1 行:检查包含 article_category=([a-z]+)article_category=lifestyle 的查询字符串是否匹配

    第 2 行:如果 URL 是 example.comexample.com/,则永久重定向到 /lifestyle%1 是 RewriteCond 反向引用,分组的部分(在括号中 ([a-z]+))的模式

    第 3 / 4 行:如果 URL 不是常规文件和目录

    第 5 行:如果 URL 以字母开头,则将 URL 重写为 index.php?article_category=$1

    【讨论】:

    • 这确实有效,但是当我执行 example.com/lifestyle 时,它​​会将我重定向到 404。如果我执行 example.com/index.php?article_category=,它不会读取 index.php 文件生活方式它有效我怎样才能使它在 index.php 中的 example.com/lifestyle 有效?
    • 它也适用于 index.php/lifestyle,但不仅适用于 example.com/lifestyle
    • 刚刚编辑,您可以使用这些规则来剥离查询字符串并进行重定向,并将 URL 重写为index.php?article_category=
    • 嗯,这也会影响其他目录中的其他 index.php 文件...有没有解决方案可以修复根目录中的特定 index.php 文件?
    猜你喜欢
    • 2015-08-20
    • 1970-01-01
    • 2012-09-25
    • 2020-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 2012-01-18
    相关资源
    最近更新 更多