Nginx redirect to URL with #
I want e.g. https://example.com/to/redirect
be redirected by nginx to https://example.com/some/url/with/#my-beautiful-id
. However, in nginx config files #
is used for comments
Is it possible? What should I write to the nginx config so it will work?
Does not work
server {
...
location /to/redirect {
...
return https://example.com/some/url/with/%23my-beautiful-id;
}
}
The #
character is not processed as start of the comment being a part of some string, e.g. https://example.com/some/url/with/#my-beautiful-id
. However it is processed as start of the comment being prepended with space, {
, }
or ;
characters (not sure this is a full list). To prevent it from being processed that way you need to quote your strings:
set $test 123#456; # $test variable value is '123#456'
set $test 123;#456; # $test variable value is '123', #456 treated as the comment
set $test "123;#456"; # $test variable value is '123;#456'
set $test '123;#456'; # $test variable value is '123;#456'
Usually there is no need to quote the string in nginx config (unless it contains a space or some other special character like {
, }
etc.), but you are always free to do it, meaning the lines
return https://example.com/some/url/with/#my-beautiful-id;
and
return "https://example.com/some/url/with/#my-beautiful-id";
are completely equal.