Search code examples
regexapache.htaccesshttp-redirectmod-rewrite

redirect all requests starting with 0x to index.html


My website will be like example.com/0xETHEREUMADDRESS.

So i want to redirect all those request starting with 0x to INDEX.HTML and index.html has already the code to the rest of work.

I need .htaccess code to redirect all starting with 0x to index.html. Here is my tried .htaccess rules file.

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/index.html$
RewriteRule (0x*)$ /index.html [L,R=302]

Solution

  • RewriteCond %{REQUEST_URI} !^/index.html$
    RewriteRule (0x*)$ /index.html [L,R=302]
    

    The regex (0x*)$ matches URLs that end-with 0, 0x, 0xx, 0xxx etc. It does not match URLs that start-with 0x, so this will not match the desired URL. The * character is a regex quantifier that repeats the preceding token 0 or more times. There is also no need for the capturing group (surrounding parentheses).

    If the rule only matches URLs that start with Ox then the condition that checks the URL is not /index.html is therefore redundant.

    The following will do what you are asking:

    RewriteRule ^0x /index.html [R=302,L]
    

    The ^ is the start-of-string anchor, so the requested URL must start with 0x. Note that the URL-path matched by the RewriteRule pattern does not start with a slash.

    However, I'd question whether you really want to "redirect" the user? (As in an external HTTP redirect - which is what this is.) Redirecting will lose the original URL and expose /index.html to your users.

    Internal "rewrite" instead

    If, however, you wish to internally rewrite the request instead so that index.html can analyse the requested URL (as you say, "index.html has already the code to the rest of work") and keep /0xETHEREUMADDRESS in the browser's address bar then remove the R=302 flag and the slash prefix on the substitution string. For example:

    RewriteRule ^0x index.html [L]
    

    Reference: