【问题标题】:Redirect using username in URL with .htaccess [closed]使用带有.htaccess的URL中的用户名重定向[关闭]
【发布时间】:2011-07-28 15:23:28
【问题描述】:

我想做一个重定向,用户在 URL 中输入他们的用户名并重定向到他们的个人资料,就像这样-> example.com/user/joe 重定向 example.com/user/profile.php?username=joe 并显然显示他们的个人资料。

我已经四处寻找如何做到这一点,但仍然没有设法让它发挥作用。 我将如何做到这一点?我应该把我的 .htaccess 文件放在哪里?

    • 管理员
    • 包括
    • 公开
      • 用户
        • profile.php
      • index.php

【问题讨论】:

    标签: php .htaccess redirect


    【解决方案1】:

    从您的目录看来,“公共”目录是您网站的文档根目录。所以,把 .htaccess 文件放在那里。

    这些都没有经过测试。但这应该让你离开地面。我会使用 mod_rewrite 来实现这一点。这样的东西应该进入你的 .htaccess 文件。

    RewriteEngine On
    RewriteRule ^user/(.+)$ user/profile.php?username=$1 [R,L]
    

    这应该可以解决您的问题。 [R] 标志将导致 Apache HTTPD 要求浏览器重定向并访问新 URL。如果您希望重定向是内部的,而用户对此一无所知,请不要使用 [R,L] 标志。

    话虽如此,我真的会这样做。

    RewriteEngine On
    
    # Canonicalize /user/foo to /user/foo/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^profile/([^/]+)$ /profile/$1/ [R=301,L]
    
    # Map /user/foo/ to foo's profile
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^profile/([^/]+)/$ profile/index.php?p=$1 [QSA]
    

    RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-d 将确保当用户请求的资源是服务器中存在的有效文件或文件夹时,不要理会所有这些重定向规则,继续前进立即提供该文件或文件夹。

    第一个RewriteRule 是为了确保如果用户忘记了斜杠,服务器会要求浏览器重定向到带有斜杠的URL。这就是 Apache HTTPD 默认的行为方式(可能是因为 mod_dir),我也会尝试在此处保留相同的行为。

    第二个RewriteRule 确保对http://example.com/user/foo/ 的请求是有效的URL,但http://example.com/user/foo/bar/ 不是。 [QSA] 标志可确保保留添加到 URL 的所有参数。

    没有[QSA] 标志,http://example.com/user/foo/?ref=related+articles 将在内部重定向到http://example.com/user/profile.php?user=foo。使用该标志,它将重定向到http://example.com/user/profile.php?user=foo&ref=related+articles,这是我更喜欢的。

    【讨论】:

    • 谢谢,正是我需要的! :D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多