need to escape # (hash/pound) character in .htacce

2020-02-11 22:53发布

The question is fairly simple but I was not able to find an answer for hours now.

What I need to do is:

RewriteRule ([^#])#(.*) $1\%23$2

Which basically means I want to url escape the freaking hash sign which comes to me from an external codepiece.

backslash (\) does not work to escape this sign... and please don't suggest using %23 instead # because it does not work as well.

(%23 does not match a # because it simply is not == %23)

4条回答
成全新的幸福
2楼-- · 2020-02-11 23:34

The hash part of a URL is not available for rewriting. When a web browser sends a URL request to a web server it sends everything up to the hash sign. The hash is only available on the client (e.g. JavaScript code can see it).

查看更多
乱世女痞
3楼-- · 2020-02-11 23:36

Search Extended Redirection in http://httpd.apache.org/docs/2.0/misc/rewriteguide.html . There is a nice solution for your question.

查看更多
做个烂人
4楼-- · 2020-02-11 23:46

.htaccess

RewriteRule  old\.php redirect.php?url=http://example.com/new.php|hash [R=301,QSA,L]

redirect.php

<?php
    $new_url = str_replace("|", "#", $_GET['url']);
    header("Location: ".$new_url, 301);
    die;
?>
查看更多
地球回转人心会变
5楼-- · 2020-02-11 23:50

I just got this working for a site following a couple of posts on this forum, I'm using a rewrite rule with NE not escape and R=301 redirect options:

RewriteRule ^galleries/([a-zA-Z0-9_-]+)$ /gallery.html#/$1 [R=301,NE,L]

This redirects all galleries/variable to /gallery.html#/variable

Edit: The important part of the rule is NE which instructs the server to parse output without escaping characters. Without this, it will try and escape the # in the rewrite rule which is what the OP is asking about.

查看更多
登录 后发表回答