Home > Net >  Redirect from a URL without a hash to a URL with a hash
Redirect from a URL without a hash to a URL with a hash

Time:03-09

On Apache, I want to create a URL redirect rule using .htaccess.

The expected incoming URL will be formed according to the following pattern:

[PROTOCOL]://[domain name]/i/[INTEGER]/[INTEGER]/[STRING]

I want the above URL to be redirected so that there is now a hash in the URL, as follows:

[PROTOCOL]://[domain name]/i/#/[INTEGER]/[INTEGER]/[STRING]

Examples

I want to go...

FROM THIS:

https://example.com/i/92/17/abcdef

TO THIS:

https://example.com/i/#/92/17/abcdef

Important: the browser must not strip out the hash in the redirected URL. I need that hash.

Why would I want to do this? Because routes for the original incoming URLs (without the hash) don't actually exist. I need javascript to examine the items that appear after the hash, and use them to make fetch requests to an API server from the browser. This is necessary because my host will only have static HTML files on it. Also I want a cosmetically-pleasing incoming URL which does not contain a hashtag (even though it will be redirected to a URL with a hashtag).

The question is, how do I achieve this with an .htaccess file that lives in the https://example.com/i/ subdirectory?

CodePudding user response:

Using mod_rewrite at the top of the .htaccess file in the /i subdirectory:

RewriteEngine On

RewriteRule ^\d /\d /[^/] $ /i/#/$0 [NE,R=302,L]

Since the .htaccess file is in the /i subdirectory, the RewriteRule pattern (first argument) matches against the [INTEGER]/[INTEGER]/[STRING] part of the URL-path (ie. relative to the directory that contains the .htaccess file).

The $0 backrereference contains the entire URL-path that is matched by the RewrietRule pattern.

The NE flag is required to prevent the # being URL-encoded (as #) in the redirect response.

  • Related