【问题标题】:How to use htaccess to rename pages and remove extensions without affecting css or js external files如何使用 htaccess 重命名页面和删除扩展而不影响 css 或 js 外部文件
【发布时间】:2012-05-02 18:32:28
【问题描述】:

我想在 htaccess 中创建一个规则来重命名我的页面,例如:

我希望 domain.com/page1 实际打开页面 domain.com/content?p=page1 或 domain.com/page2 实际上打开了页面 domain.com/content?p=page2

为此,我有一个非常简单的正则表达式:

RewriteRule (.*)$ /content.php?p=$ [L]

现在的问题是,这会影响所有内容,甚至会影响到 style.css 或 functions.js 等文件,甚至是 images/logo.jpg。

所以我正在寻找一个正则表达式,如果它们没有点 (.) 或斜杠 (/),它将转发我的所有页面

例如:

domain.com/blog  true
domain.com/home?lang=en true
domain.com/styles.css false
domain.com/image.png false
domain.com/folder/file false

谢谢!

【问题讨论】:

    标签: regex .htaccess redirect file-rename


    【解决方案1】:

    请看下面的代码:

    <IfModule mod_rewrite.c>
        RewriteEngine on
    
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
    
        RewriteRule ^(.*)$ content.php?p=$1 [L,QSA]
    </IfModule>
    

    如果请求的 URL 不是目录也不是文件,将在下一行执行。

    干杯!

    【讨论】:

      【解决方案2】:

      这是您需要放入 .htaccess 文件中的代码:

      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-l
      RewriteRule ^([^/.]+)/?$ content.php?p=$1 [L,QSA]
      

      【讨论】:

      • !-l 用于在请求的 URI 是有效链接时避免 RewriteRule。
      猜你喜欢
      • 1970-01-01
      • 2019-01-06
      • 2020-05-14
      • 2017-06-07
      • 1970-01-01
      • 1970-01-01
      • 2015-01-25
      • 2016-12-28
      相关资源
      最近更新 更多