How to regex a url to redirect user

How to regex a url to redirect user - .htaccess files are extremely useful in many cases for users who either do not have root permissions or for users who simply aren't comfortable in making changes in their web server's configuration file. Trying to debug .htaccess not working isn't always the easiest thing to do, however, hopefully by checking the discuss below mentioned about htaccess, redirects, mod-rewrite, regular-expression, .htaccess common problems as well as the troubleshooting tips, you'll have a better grasp on what you may have to modify to get your .htaccess file running smoothly.Problem :


Using the regex and the .htaccess file, I want to redirect users to a certain URL.



I want to redirect:




  • http://www.example.com/* but not http://www.example.com/CDadmin/*



I have tried the following:




  • http://www.example.com/CDadmin/[*-^$CDadmin/*]



But does not work when I test with regex101.


Solution :

Since you've not clarified the specifics of your question, I'll make some assumptions:




  • You wish to redirect to a different domain. eg. example.net

  • example.net points to a different server.

  • /CDadmin is a physical directory on the filesystem.







  1. At the top of the .htaccess file in the document root of example.com, place the following:



    RewriteEngine On
    RewriteRule (.*) http://example.net/$1 [R=302,L]


    The only regex here is (.*) - which will basically redirect everything. (Read on...)



    This is a temporary (302) redirect. Change to a 301 if you want to make it permanent.


  2. Then, in the .htaccess file in the /CDadmin subdirectory, simply enable the rewrite engine:



    RewriteEngine On


    This will effectively override the mod_rewrite directives in the parent .htaccess file, so nothing will be redirected when accessing /CDadmin/<something>.



Additionally, if you would like to do some further testing, give the htaccess tester tool a try. It allows you to specify a certain URL as well as the rules you would like to include and then shows which rules were tested, which ones met the criteria, and which ones were executed.

Comments

Popular posts from this blog

Rewrite in Mediawiki, remove index.php, .htaccess

.htaccess rewrite wildcard folder paths from host

Using .htaccess to set a cookie and 301 redirect