【问题标题】:Regex to avoid "dirty" web links正则表达式避免“脏”的网页链接
【发布时间】:2011-11-06 10:03:32
【问题描述】:

如果这是我的文件的实际 URL:

http://www.example.org/posts.php?post=example-post-name

在我的 .htaccess 文件中,当用户提交时,如何使用正则表达式获取此路径:

http://www.example.org/posts/example-post-name

到目前为止,我已经提出了一些示例(其中还包括 www 重定向):

RewriteEngine On

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

RewriteCond %{REQUEST_URI} !(\.[^./]+)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule (.*) /$1.php [L]
RewriteRule ^posts/([A-Za-z])/$ /posts.php?post=$1

但是我运气不好,谁能告诉我哪里出错了?

【问题讨论】:

    标签: html regex .htaccess


    【解决方案1】:

    您需要在A-Za-z 组之后使用+ 来指示一个或多个字符,并且您还需要在该组的末尾添加一个-。最后,/? 表示最后的斜线可能存在也可能不存在。

    最后,添加[L] 以确保不再处理重写规则。

    RewriteEngine On
    
    RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
    RewriteRule ^(.*) http://%1/$1 [R=301,L]
    
    # First rewrite the posts:
    RewriteRule ^posts/([A-Za-z-]+)/?$ /posts.php?post=$1 [L]
    
    # ing0 edit: add in dirs that need changing back.
    # (I dont know if there is an easier way to do this).
    RewriteRule ^posts/css/(.*)$ /css/$1 [L]
    RewriteRule ^posts/img/(.*)$ /img/$1 [L]
    # etc
    
    # Then, if it's not a real file and doesn't already end in .php
    # Note change here ...
    RewriteCond %{REQUEST_URI} !\.php$
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    # redirect it to PHP.
    RewriteRule (.*) /$1.php [L]
    

    【讨论】:

    • 如果我添加这个,我会得到一个Internal Server Error
    • !ing0 请查看您的服务器错误日志以了解实际错误是什么。
    • 只是在这台服务器上寻找日志。如果我在你的正则表达式之后将正则表达式添加到文件末尾(RewriteRule (.*) /$1.php [L]),我会得到 500 个服务器错误。如果我之前放过,网站会加载但无法正常工作。
    • @ing0 请参阅上面的更改。您可能会使用最后一条添加 .php 的规则进入无限重定向循环。我更改了RewriteCond,因此它不会重写已经以.php 结尾的请求。
    • 啊,它成功了。谢谢。我刚刚编辑了你的答案,重写了包含 css 或图像目录的 dir。
    【解决方案2】:

    为什么不使用:

    RewriteRule ^posts/(.*)/$ posts.php?post=$1
    

    【讨论】:

      【解决方案3】:

      我认为您需要匹配整个网址,而正则表达式不太正确。试试这个:

      RewriteRule ^(.*)/posts/([\w-]+)$ $1/posts.php?post=$2
      

      如果它只匹配 url 的非基本部分,这个:

      RewriteRule ^posts/([\w-]+)$ posts.php?post=$1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-28
        • 2010-09-05
        • 2021-05-30
        • 2023-01-24
        • 1970-01-01
        • 2011-04-13
        • 2012-02-07
        • 2016-07-17
        相关资源
        最近更新 更多