【问题标题】:Clean url for static and dynamic pages静态和动态页面的清理 url
【发布时间】:2015-06-01 05:52:51
【问题描述】:

我的网站混合了没有变量的静态页面(例如:about.php)和一些动态页面(例如:searchresults.php?a=1&b=2)

现在我的 .htaccess 允许显示静态页面,但不允许显示动态页面。然而,我为使动态页面工作所做的一切都破坏了静态页面的干净 URL。

RewriteEngine On

DirectoryIndex index.php index.html

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
RewriteRule ^([^\.]+)$ $1.html [NC,L]

我希望最终结果如下所示:

http://example.com/about.php -> http://example.com/about

http://example.com/searchresults.php?a=1&b=2 -> http://example.com/searchresults/1/2

我想做的事可能吗?

【问题讨论】:

    标签: php .htaccess mod-rewrite clean-urls


    【解决方案1】:

    是的,这是可能的。

    首先,您需要更改规则以去除扩展名。目前,您有两个匹配任何内容的规则(意味着第二个永远不会触发),而第二个规则没有条件。

    其次,您的搜索规则需要明确指定。

    您的.htaccess 文件现在应该如下所示:

    RewriteEngine on
    
    # Rewrite the search page
    
    RewriteRule ^searchresults/([^/]+)/([^/]+)/?$ searchresults.php?a=$1&b=$2 [QSA,L]
    
    # Allow requests without php/html extensions
    
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^([^\.]+)$ $1.php [L]
    
    RewriteCond %{REQUEST_FILENAME}.html -f
    RewriteRule ^([^\.]+)$ $1.html [L]
    

    【讨论】:

    • 谢谢你,这很完美!只有一个问题...我在服务器上的 .js 和 .css 文件的相对链接(在包含的 header.php 中)在搜索页面上不起作用。有什么办法可以解决这个问题,还是我应该坚持使用绝对 URL?
    • 如果您使用<link rel="stylesheet" href="css/mystyles.css">,例如,您可以简单地在前面加上一个正斜杠,使其相对于域的根:href="/css/mystyles.css"
    【解决方案2】:

    为您的 htaccess 文件尝试下面的代码行。

    RewriteEngine on
    RewriteRule aboutus/$               about.php   [NC,L,QSA]
    RewriteRule searchresults/(.*)/(.*)/$           searchresults.php?a=$1 & b=$2   [NC,L,QSA]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-03
      • 2012-04-15
      • 1970-01-01
      • 2014-03-28
      • 2012-11-05
      • 1970-01-01
      • 2014-09-22
      相关资源
      最近更新 更多