【问题标题】:htaccess - remove .jpg from the end of the url, then process all rewriting ruleshtaccess - 从 url 末尾删除 .jpg,然后处理所有重写规则
【发布时间】:2019-09-23 22:16:59
【问题描述】:

我正在尝试创建一些将获取此 URL 的 URL 重写规则:

https://example.com/abc/123.jpg

并改写为以下url:

https://example.com/?p=abc&u=123

所以它会:

  1. 忽略“.jpg”
  2. 将第一个“/”后面的值设置为p参数
  3. 将第二个“/”后面的值设置为u参数

对于#2 和#3,我有这个(而且效果很好):

RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ ?p=$1 [QSA]
RewriteRule ^([a-zA-Z0-9_-]+)/$ ?p=$1 [QSA]

RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ ?p=$1&u=$2 [QSA]
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/$ ?p=$1&u=$2 [QSA]

但是,当我在网址末尾有“.jpg”时,我会收到 apache 错误“未找到”。

有谁知道在这种情况下我需要向 .htaccess 添加什么规则以忽略“.jpg”?

谢谢!

【问题讨论】:

    标签: .htaccess url-rewriting


    【解决方案1】:

    最后,您必须将最后一个 .jpg.jpeg 设为可选。您可以使用以下两条规则:

    RewriteEngine On
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([\w-]+)(?:\.jpe?g|/)?$ ?p=$1 [L,NC,QSA]
    
    RewriteCond %{REQUEST_FILENAME} !-d    
    RewriteRule ^([\w-]+)/([\w-]+)(?:\.jpe?g|/)?$ ?p=$1&u=$2 [L,NC,QSA]
    

    注意\w 等同于[a-zA-Z0-9_]

    【讨论】:

      【解决方案2】:

      您可以在每个规则上添加 .jpg 以仅匹配 .jpg 结尾网址

      RewriteRule ^([a-zA-Z0-9_-]+)\.jpg$ ?p=$1 [QSA]
      RewriteRule ^([a-zA-Z0-9_-]+)\.jpg/$ ?p=$1 [QSA]
      RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)\.jpg$ "?p=$1&u=$2" [QSA]
      RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)\.jpg/$ ?p=$1&u=$2 [QSA]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-30
        • 1970-01-01
        • 1970-01-01
        • 2018-07-13
        • 2017-07-22
        相关资源
        最近更新 更多