【问题标题】:How to rewriterule URL using .htaccess如何使用 .htaccess 重写 URL
【发布时间】:2017-06-26 11:24:18
【问题描述】:

如何重写这样的链接

http://stanime.pe.hu/content.php?idf=15&link=Katsugeki--Touken+Ranbu

http://stanime.pe.hu/15/Katsugeki--Touken+Ranbu

我使用 Urlencode 和 urldecode 对我的网址进行编码和解码

在使用 latin1_swedish_ci 的数据库排序中

所以,space 将替换为 +/ 替换为 %2f 等等......

这是我的 .htacces 代码

    RewriteEngine On

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} \s/+content\.php\?link=([^\s&]+) [NC]
RewriteRule ^ /%1? [R=302,L,NE]

# internal forward from pretty URL to actual one
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ content.php?link=$1 [B,L,QSA]

【问题讨论】:

    标签: php apache .htaccess mod-rewrite


    【解决方案1】:

    首先你需要在你的虚拟主机或者http.conf文件中添加这个指令:

    AllowEncodedSlashes On
    

    这将允许编码的斜杠字符,即 URL 中的%2F

    您可以在站点根目录 .htaccess 中使用这些规则:

    RewriteEngine On
    
    # external redirect from actual URL to pretty one
    RewriteCond %{THE_REQUEST} \s/+content\.php\?idf=([^\s&]+)&link=([^\s&]+) [NC]
    RewriteRule ^ /%1/%2? [R=302,L,NE]
    
    # internal forward from pretty URL to actual one
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([\w-]+)/(.+)$ content.php?idf=$1&link=$2 [B,L,QSA]
    

    【讨论】:

    • 因为我使用免费托管我无法访问 apache 文件。还有其他方法吗?
    • 不幸的是,AllowEncodedSlashes 只允许在 Apache 配置中使用。
    • 哈哈,听到这个消息很难过...我尝试在我的专用文件中查找 httpd.conf,但在 /etc/apache2 中找不到,没有名为 httpd.conf 的文件
    • 当我有相同的标题时我发现一个错误,然后我修改我的链接是这样的? http://stanime.pe.hu/content.php?idf=15&link=Katsugeki--Touken+Ranbu我想要的链接是这样的http://stanime.pe.hu//15/Katsugeki--Touken+Ranbu
    • 啊,但这是一个不同的 URL,因为您现在有 2 个查询参数。
    【解决方案2】:

    您必须添加如下字符规则。因为您的数据是字符形式的,而不仅仅是您在此处定义的 url 中的数字。

      RewriteRule    ^content/([A-Za-z0-9-_]+)/?$    content.php?link=$1 [NC,L]  
    

    【讨论】:

    • 仍然找不到对象 http://localhost/web/content/Fate%2FApocrypha RewriteRule ^content/([0-9a-zA-Z]+)/?$ content.php?link=$1 [NC,L]
    • 如果你必须检查这个 url 那么发生了什么? localhost/web/content/Fate-Apocrypha
    • 只为没有空格或特殊字符的url工作..当我尝试打开stanime.pe.hu/content/Katsugeki%2FTouken+Ranbu错误显示时,你可以自己尝试stanime.pe.hu
    • 好的,为什么要在 url 中添加空格?您可以删除链接中制作网址之前的空格。为此,您可以使用 str_replace 函数
    • 哈哈哈,我使用原生 php 创建我的网站,我不太明白如何路由正确的 URL,url 根据标题生成
    猜你喜欢
    • 2020-04-09
    • 2011-03-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2012-10-06
    相关资源
    最近更新 更多