How to deal with "#" in a query string in mod_rewrite?

by dejuan.watsica , in category: SEO , a year ago

How to deal with "#" in a query string in mod_rewrite?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

3 answers

by jose_gulgowski , a year ago

@dejuan.watsica 

In Apache mod_rewrite, the "#" symbol is treated as a special character that indicates the beginning of a URL fragment, which is not sent to the server. To use "#" in a query string in mod_rewrite, it needs to be URL-encoded as "%23". Here is an example:

1
RewriteRule ^example/([^/]+)/([^/]+)/?$ /newpage.php?var1=$1&var2=$2 [L,QSA]


With this rule, a URL like "example/value1/value2/#fragment" will be rewritten to "newpage.php?var1=value1&var2=value2%23fragment".

by percy_bauch , 4 months ago

@dejuan.watsica 

To address the special character "#" in a query string in mod_rewrite, you can use the NE (noescape) flag. The NE flag prevents the URL from being escaped and allows the "#" character to be included in the query string.


Here is an example:

1
RewriteRule ^example/([^/]+)/([^/]+)/?$ /newpage.php?var1=$1&var2=$2#%{QUERY_STRING} [NE,L]


With this rule, a URL like "example/value1/value2/#fragment" will be rewritten to "newpage.php?var1=value1&var2=value2#fragment". The NE flag ensures that the "#" character is not escaped.


Note that the %{QUERY_STRING} variable is used to include the original query string in the rewritten URL. This is optional and can be omitted if you don't need to include the original query string.

Member

by dorothea , 4 months ago

@dejuan.watsica 

I apologize for the incorrect information provided earlier. The NE flag is not applicable in this case as it only affects the result of the rewrite, not the processing of the query string.


In mod_rewrite, the "#" symbol is inherently problematic because it represents the beginning of a URL fragment and is not sent to the server. Therefore, it is not possible to directly handle the "#" symbol in the query string using mod_rewrite alone.


One possible workaround is to use the [B] flag, which escapes the special characters in the rewritten URL. Here is an example:


1


RewriteRule ^example/([^/]+)/([^/]+)/?$ /newpage.php?var1=$1&var2=$2#fragment [B,L]


With this rule, a URL like "example/value1/value2/" will be rewritten to "newpage.php?var1=value1&var2=value2%23fragment". The "#" symbol is encoded as "%23", allowing it to be included in the query string.


However, it's important to note that the "#" symbol in the rewritten URL will still be interpreted as the beginning of a URL fragment by the client's web browser. If you need to use the "#" symbol in a way that affects server-side processing, you may need to consider alternative approaches or other technologies.