【问题标题】:htaccess clean profile linkshtaccess 清理个人资料链接
【发布时间】:2012-02-19 19:44:58
【问题描述】:

目前我正在使用以下 HTACCESS 代码

RewriteEngine On

# Lose the www
RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,NC,L]

# Clean profile URLs
RewriteRule ^([a-zA-Z0-9_-]+)(/?)$ profile.php?user=$1

所以当我转到http://mysite.com/username 时,链接确实有效,我看到了个人资料。但我仍然可以使用http://mysite.com/profile.php?user=username

我想要的是第二次被定向到http://mysite.com/username 的简短版本。

另一个问题是,当我浏览http://www.mysite.com/username 时,它会将url 重写为http://mysite.com/profile.php?user=username

另外,对于某些文件夹,例如我的图像文件夹,我该如何避免这种情况?如果我转到图像文件夹,我会得到http://mysite.com/images/?user=images

另外,如果干净的 url 后面有一个斜线,页面的行为会很奇怪。

【问题讨论】:

    标签: .htaccess url-rewriting


    【解决方案1】:

    如果该网站尚未上线,我不会担心 /profile.php?user=username 网址。由于人们必须知道有一个 php 文件名为 profile.php。如果您从未在 html 中直接创建任何指向 profile.php 的链接,那么没人会知道。

    如果网站已经上线,请告诉我们。

    至于图片问题。

    RewriteCond $1 !^images/
    RewriteRule ^([a-zA-Z0-9_-]+)(/?)$ profile.php?user=$1
    

    也做一个 css 和/或 js 文件夹

    RewriteCond $1 !^(images|css|js)/
    RewriteRule ^([a-zA-Z0-9_-]+)(/?)$ profile.php?user=$1
    

    尾斜线的最后一个问题很可能与在您的 html 中使用相对 url 有关。尝试将href="path/resource.ext" 替换为href="/path/resource.ext"src="..." 等也一样。

    【讨论】:

    • 下次删除您的问题。我不喜欢浪费我的时间:-)
    【解决方案2】:

    您需要在更改 url 规则上添加最后一个操作。我将代码更改为以下内容:

    # Lose the www
    RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
    RewriteRule ^(.*)$ http://%1/$1 [R=301,NC,L]
    
    # Exclude existing files from redirect
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^.* - [L]
    
    # Clean profile URLs
    RewriteRule ^([^/]*)\/$ http://businessgame.be/$1 [R=301]
    RewriteRule ^([^/]*)(/?)$ profile.php?user=$1
    

    这似乎效果很好。

    【讨论】:

      猜你喜欢
      • 2018-11-04
      • 2014-10-09
      • 1970-01-01
      • 2012-02-06
      • 2012-01-20
      • 2015-07-02
      • 1970-01-01
      • 2014-11-13
      • 2013-04-29
      相关资源
      最近更新 更多