【问题标题】:Cant get .htaccess to work proper无法让 .htaccess 正常工作
【发布时间】:2013-10-16 09:17:03
【问题描述】:

我正在做一个 URL-Shortener,我试图让它对 URL 友好。目前我的地址是这样输入的“example.com/index.php?name=sitename”,我希望它像“example. com/sitename".. 我想我可以使用一些很酷的重写规则,但我无法让它工作..

我做了类似的事情,但它不会工作

Options All -Indexes
DirectoryIndex index.php index.html index.htm
RewriteEngine On
RewriteRule ^([^/]*)/$ /index.php?name=$1 [L]

但我不知道:s?

【问题讨论】:

  • 这个设置有什么问题?

标签: php regex apache .htaccess mod-rewrite


【解决方案1】:

这是您需要放入DOCUMENT_ROOT/.htaccess的代码

Options All +FollowSymLinks -MultiViews -Indexes
DirectoryIndex index.php index.html index.htm
RewriteEngine On

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+index\.php\?name=([^\s&]+) [NC]
RewriteRule ^ /%1? [R=301,L]

# internal forward from pretty URL to actual one
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/?$ /index.php?name=$1 [L,QSA]

参考:Apache mod_rewrite Introduction

【讨论】:

    【解决方案2】:

    您的正则表达式将在域后有多个 / 的 URL 上失败,因为 [^/] 在看到其中一个字符时立即停止,然后它会查找带有 /$ 的最后一个斜杠,即并非总是如此。

    假设您要转换这些网址

    example.com/HiThere
    example.com/Your/Page
    

    到:

    example.com/index.php?name=HiThere
    example.com/index.php?name=Your/Page
    

    试试这个重写规则:

    RewriteRule ^(.*?)/$ /index.php?name=$1 [L]
    

    这将查找所有带有(.*?) 的字符,直到它到达最后一个/。不过,我不是 100% 确定 [L] 标志。

    【讨论】:

    • 现在我的 URLS 看起来像这样 example.com/index.php?name=Avetile 我希望是:example.com/Avetile
    • 你应该反过来想。如果用户访问example.com/Avetile,该页面实际上并不存在。服务器将查看 .htaccess 并查看将 URL 转换为 example.com/index.php?name=Avetile 的规则,该规则确实存在。然后它以名字加载该页面。
    • 他在 URL-Shortener 中使用它并且没有重复 '/' 的机会
    • 这也会导致无限循环。
    【解决方案3】:

    最简单的方法是使用404错误指向index.php,然后使用php获取sitename .htaccess 文件

    ErrorDocument 404 /index.php
    

    PHP 代码

    <?php 
    $sitename=substr(strrchr($_SERVER["REQUEST_URI"],"/"),"1");
    

    现在只需访问“example.com/sitename”,站点名称将存储在$sitename

    还有if($sitename==""){//Show your HomePage}

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-07
      • 2012-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多