Nginx rewrite first char host

277 Views Asked by At

There is a rule for htaccess:

RewriteCond %{HTTP_HOST} ^(([\w]{1})[\w.]+)$
RewriteRule ^root/(.*)$ site_link/%1/$1 [L]

It needs to be converted into a rule for Nginx. And I know that IF is evil.

PS Thank you very much.

1

There are 1 best solutions below

2
On

Your HTTP Host regex is inappropriate.

Your are trying to somehow re-implement some domain name validation on server side while DNS won't in any way resolve a broken domain name format to your server IP.

Moreover your regex would let falsely formatted "domain names" go in if it was used : [\w.]+ matches [a-zA-Z0-9_.]+, so you would allow a range of formats that are already rejected by DNS. See RFCs 1123, 2782 and 3696 for domain names format specifications.

So for this part : abandon the idea. Now, the answer is simple as you don't need any condition :

server {

    server_name my.domain.tld

    location / {
        rewrite ^/root/(.*)$ /site_link/$host/$1;
    }

}