【问题标题】:.htaccess for friendly URL.htaccess 用于友好的 URL
【发布时间】:2015-03-04 12:52:29
【问题描述】:

我想为我的一个项目创建一个友好的 URL。目前我的网址是http://example.com/profile.php?user=someprofile,我想把它改成http://example.com/someprofile。我尝试了下面的 htaccess,但我的 CSS 和图像文件没有加载。

RewriteEngine on

RewriteCond $1 !^(profile\.php|assets|editor|css|js|scripts|images|img|media|xml|user_guide|robots\.txt|favicon\.ico)
RewriteRule ^g/([^/\.]+)/?$ profile.php?user=$1 [L]
<Files profile>
    ForceType application/x-httpd-php
</Files>

我如何做到这一点?

【问题讨论】:

标签: php regex apache .htaccess friendly-url


【解决方案1】:

这听起来像是相对/绝对 URL 的问题。由于您在 URL 的开头添加了 /g/,这改变了相对 URI 基础,因此您的所有相对链接都将被破坏。您需要将链接更改为绝对链接或将相对 URI 基础添加到页面标题:

<base href="/" />

【讨论】:

    【解决方案2】:

    让你的 .htaccess 像这样:

    RewriteEngine on
    
    # If the request is not for a valid directory
    RewriteCond %{REQUEST_FILENAME} !-d
    # If the request is not for a valid file
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/?$ profile.php?user=$1 [L,QSA]
    

    css/js/images 路径问题: 最好在 css、js、图像文件中使用绝对路径而不是相对路径。这意味着您必须确保这些文件的路径以 http:// 或斜杠 / 开头。

    否则您可以尝试在页面 HTML 的 &lt;head&gt; 部分添加:&lt;base href="/" /&gt;,以便从该 URL 而非当前页面的 URL 解析每个相对 URL。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-31
      • 2012-06-03
      • 2012-04-25
      • 1970-01-01
      • 2015-12-16
      • 2011-05-29
      相关资源
      最近更新 更多