.htaccess and robots.txt rewrite url how to

2019-06-09 08:23发布

问题:

Here is my code for .htaccess

RewriteEngine on
RewriteRule (.*) index.html

Problem : when visit mydomain.com/robots.txt then page again redirect to index.html
Required :

if(url contain robots.txt) Then   
    redirect to mydomain.com/robots.txt   
else   
    redirect to index.html

回答1:

Try this:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.html

Basically, those two RewriteCond tell apache to rewrite the URL only if the requested file (-f) or directory (-d) doesn't exists (the ! serves as a negation).

Alternatively, if you need it just for robots.txt you can use something like:

RewriteCond %{REQUEST_URI} !^/robots.txt$

instead of the two RewriteCond above.