Tag Archives: linux apache htaccess

Some tips on using .htaccess

Imagine you have a website running on http://myserver.com/site1/ and you need to redirect all the traffic to other website that is located on http://someguyserver.com/modules/app/good_app/

The site running on someguyserver.com has the same structure as your site:

  • http://myserver.com/site1/pagina3.html -> http://http://someguyserver.com/modules/app/good_ap/pagina3.html
  • http://myserver.com/site1/hello_world/index.html<7a> -> http://http://someguyserver.com/modules/app/good_ap/hello_world/index.html

    This can be done defining the following rules on the .htaccess file in the root folder of http://myserver.com/site1:

    1
    2
    3
    4
    RewriteEngine on

    ## Redirect the requests to http://myserver.com/site1 into someguyserver.com
    RewriteRule ^(.*)$ http://someguyserver.com/modules/app/good_app/$1 [P]

    The [P] flag is for Proxy which means request will be proxied to the new destination but the user will keep seeing the same URL.

    Now, imagine that all the images, css and javascript on the HTML files inside http://myserver.com/site1/ are being referenced from the root folder like:

    1
    2
    <link rel="stylesheet" type="text/css" media="screen" href="/css/conventional.css" />
    <script type="text/javascript" src="/js/jquery.js"></script>

    This means that our redirect using .htaccess inside the /site1/ directory would not work. To solve this, we need to place a .htaccess file in the root directory of the domain (the directory that serves http://myserver.com) but what if myserver.com is a website itself or has other /site*/ websites that you don’t want to redirect the requests into http://someguyserver.com)?

    This can be done by using a RewriteCond to trigger the RewriteRule. And our RewriteCond can be based on the HTTP_REFERER of the request that will let us know if the request is coming from http://myserver.com or not):

    1
    2
    3
    4
    5
    6
    RewriteEngine on

    ## Requests for css, images or js (/css or /images or /js) that are coming from
    ## http://myserver.com/site1 will be redirected to someguyserver.com
    RewriteCond %{HTTP_REFERER} http://www.myserver.com/site1 [NC]
    RewriteRule ^(css|images|js)/(.*)$ http://www.someguyserver.com/$1/$2 [P]

    If you keep struggling with .htacess files and are not understanding why rules are not being matched and why it is not working, you can enable logging by placing the following in the virtual host configuration for the web site.

    1
    2
    RewriteLog "/var/www/myserver.com/logs/rewrite.log"
    RewriteLogLevel 5

    Note: This requires having MOD_REWRITE installed and enabled on Apache.