• logo
  • PHP
  • PHP OOPs
  • script
    • JavaScript
    • JQuery
    • Ajax
    • AngularJs
    • VueJs
    • NodeJs
    • ReactJs
  • wordpress
  • Codeigniter
  • Codeigniter 4
  • Laravel
  • Python
  • MySql
  • Json
  • C
  • C++
  • More ...
    • Cakephp Framework
    • MongoDb
    • MySqli PDO
    • .htaccess
    • HTML 5
    • CSS
    • SEO
    • DCA

PHP Tutorials

  • htaccess

say Customer Say

Read More

Home テつサ .htaccess テつサ  About .htaccess



What is htaccess

.htaccess is a configuration file for use on web servers running on the web apache server software. when a .htaccess file is placed in a directory which in turn loaded via the Apache web server, then the .htaccess file detected and executed by the Apache server software. .htaccess files can be utilized to modify the setup of the Apache server software to empower additional functionality and fetures that the apache web server softwatre brings to the table. We can use the .htaccess file for alteration various configuration in apache web server software. Some of them are listed below:

  • ErrorDocuments :-
  • Password protection :-
  • Redirection:-
  • Deny visitors by IP address:-
  • Adding MIME types
  • GENERAL INSTRUCTIONS

    Create a plain text .htaccess file.
    Use FTP to upload the file to the document root of the appropriate domain. If your domain is example.com, you should upload the file to: www.example.com/

    Introduction :- Url rewriting means modify url's appearance. rebuild an url to a new url or make a user or search engine friendly url. url rewrite depends on mod_rewrite must be enabled on Apache server. The main purpose of url rewrite to make clean url most of sites have dynamic variables in url like:-http://example.com/example.php?x=xx&y=yyThis is not a readable url or not useful for search engine and also not define to page purpose so using url rewrite we can get a shorter and standard url like:-http://example.com/example/xx/yyThese type of url easier to read, remember and much clean. we can also do more effort to make it more clean.

    Url rewrite Flags :- Some of common used url rewrite flags
    L - Last, to stop processing no further rules will be processed
    N - Next, flag start ruleset again from the top
    NC - NOcase, means case-insensitive
    R - Redirect
    QSA - query string append

    How to redirect www.itechtuto.com to itechtuto.com

    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^www¥.styleguts¥.com$ [NC]
    RewriteRule ^/?$ "http¥:¥/¥/styleguts¥.com¥/" [R=301,L]
    RewriteRule ^([^¥.]+)$ $1.php [NC,L]



    How to redirect itechtuto.com to http://itechtuto.com


    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^www¥.styleguts¥.com [NC]
    RewriteRule ^(.*)$ http://styleguts.com/$1 [L,R=301]

    Examples of url rewriting :-

    Remove.php extension from url :- To remove.php extension like if you want change http://example.com/myfile.php to http://example.com/myfile add below code to .htaccess
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^¥.]+)$ $1.php [NC,L]



    if you want to give a specfic name to file like http://www.example.com/myfile.php to http://www.example.com/something

    RewriteEngine On
    RewriteRule ^something/?$ myfile.php [NC,L]


    Redirect non www to www url :-

    if you want url with www redirection or add a www in url add below code to your .htaccess.


    RewriteCond %{HTTP_HOST} ^example.com$
    RewriteRule (.*) http://www.example.com/$1 [R=301,L]


    Remove www from url.

    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^www¥.gamesaroma¥.com$ [NC]
    RewriteRule ^/?$ "http¥:¥/¥/gamesaroma¥.com¥/" [R=301,L]
    RewriteRule ^([^¥.]+)$ $1.php [NC,L]


    Redirect errror page.

    • ErrorDocument 404 /error-code.php
    • ErrorDocument 400 /error-code.php
    • ErrorDocument 401 /error-code.php
    • ErrorDocument 403 /error-code.php
    • ErrorDocument 500 /error-code.php
    • ErrorDocument 502 /error-code.php
    • ErrorDocument 504 /error-code.php

    # If we don't have mod_rewrite installed, all 404's
    # can be sent to index.php, and everything works as normal.
    # Submitted by: ElliotHaughin
    ErrorDocument 404 /index.php


    Remove index.php from url in Codeigniter


    RewriteEngine On
    RewriteBase /gmax_Admin
    ##RewriteRule ^$ /gmax_admin/index.php [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]



    Dynamic pattern :-

    rewrite with specific name applied for a single url rewrite for multiple or dynamic url rewriting you need to use regular expressions in pattern like :-
    if you using query string in url like http://www.example.com/myfile.php?id=7 and want to change http://www.example.com/myfile/7 then use


    RewriteRule ^myfile/([a-zA-Z0-9]+)/?$ myfile.php?id=$1 [NC,L,QSA]
    # getting all numeric and alphabet
    // if you want to check with only numeric
    RewriteRule ^myfile/([0-9]+)/?$ myfile.php?id=$1 [NC,L,QSA]
    #applying numeric pattern



    Some of meta character used in regular expressions:-


    . - any character
    * - preceding start from zero
    + - preceding start from one
    {} - min to max quantifier
    ? - ungreedy modifier
    ^ - must be start
    $ - end of string
    [] - class, apply more match
    - - range if used in class
    () - group
    | - or
    ¥ - escape character



    This .htaccess file will redirect http://example.com/folder1/ to http://example.com/folder2/.

    Options +FollowSymLinks
    RewriteEngine On
    RewriteRule ^folder1.*$ http://example.com/folder2/ [R=301,L]



    This .htaccess file will redirect http://example.com/folder1/ to plain http://example.com/.

    Options +FollowSymLinks
    RewriteEngine On
    RewriteRule ^folder1.*$ http://example.com/ [R=301,L]



    This .htaccess file will redirect http://example.com/folder1/file.html to http://example.com/folder2/file.html.

    Options +FollowSymLinks
    RewriteEngine On
    RewriteRule ^folder1/(.*)$ http://gs.mt-example.com/folder2/$1 [R=301,L]



    Code explanation

  • 1. Options +FollowSymLinks is an Apache directive, prerequisite for mod_rewrite.
  • 2. RewriteEngine On enables mod_rewrite.
  • 3. RewriteRule defines a particular rule.
  • 4. The first string of characters after RewriteRule defines what the original URL looks like. There's a more detailed explanation of the special characters at the end of this article.
  • 5. The second string after RewriteRule defines the new URL. This is in relation to the document root (html) directory. / means the html directory itself, and subfolders can also be specified. $1 at the end matches the part in parentheses () from the first string. Basically, this makes sure that sub-pages get redirected to the same sub-page and not the main page. Leave it out to redirect to the main page. (It is left out in the first two examples for this reason. If you don't have the same content in the new directory that you had in the old directory, leave this out.)
  • 6. [R=301,L] - this performs a 301 redirect and also stops any later rewrite rules from affecting this URL (a good idea to add after the last rule). It's on the same line as RewriteRule, at the end.


  • This .htaccess file will redirect http://example.com/file.html to http://example.com/folder1/file.html:

    Options +FollowSymLinks
    RewriteEngine On
    RewriteCond %{HTTP_HOST} example.com$ [NC]
    RewriteCond %{HTTP_HOST} !folder1
    RewriteRule ^(.*)$ http://example.com/folder1/$1 [R=301,L]



    Code explanation

  • 1. Options +FollowSymLinks is an Apache directive, prerequisite for mod_rewrite.
  • 2. RewriteEngine On enables mod_rewrite.
  • 3. RewriteCond %{HTTP_HOST} shows which URLs we do and don't want to run through the rewrite.
  • In this case, we want to match example.com.
  • ! means "not." We don't want to rewrite a URL that already includes folder1, because then it would keep getting folder1 added, and it would become an infinitely long URL.
  • 4. [NC] matches both upper- and lower-case versions of the URL.
  • 5. RewriteRule defines a particular rule.
  • 6. The first string of characters after RewriteRule defines what the original URL looks like. There's a more detailed explanation of the special characters at the end of this article.
  • 7. The second string after RewriteRule defines the new URL. This is in relation to the document root (html) directory. / means the html directory itself, and subfolders can also be specified.
  • $1 at the end matches the part in parentheses () from the first string. Basically, this makes sure that sub-pages get redirected to the same sub-page and not the main page. Leave it out to redirect to the main page of the subdirectory.
  • 8. [R=301,L] - this performs a 301 redirect and also stops any later rewrite rules from affecting this URL (a good idea to add after the last rule). It's on the same line as RewriteRule, at the end.

  • This .htaccess file will redirect http://example.com/ to http://www.example.com/.

    Options +FollowSymLinks
    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^example.com [NC]
    RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]


    This .htaccess file will redirect http://example.com/ to https://example.com/.

    RewriteEngine On
    RewriteCond %{SERVER_PORT} 80
    RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]



    REGULAR EXPRESSIONS

    ^ begins the line to match.
    $ ends the line to match.
    So, ^folder1$ matches folder1 exactly.
    . stands for "any non-whitespace character" (example: a, B, 3).
    * means that the previous character can be matched zero or more times.
    So, ^uploads.*$ matches uploads2009, uploads2010, etc.
    ^.*$ means "match anything and everything." This is useful if you don't know what your users might type for the URL.
    () designates which portion to preserve for use again in the $1 variable in the second string. This is useful for handling requests for particular files that should be the same in the old and new versions of the URL.



    Redirect an old domain to a new domain

    If you had an old domain such as example.com, and now you decided you actually want to use example.net for the website. You could setup a 301 redirect for the entire domain, so that old links to example.com carry over.
    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^example.com [NC,OR]
    RewriteCond %{HTTP_HOST} ^www.example.com [NC]
    RewriteRule ^(.*)$ http://example.net/$1 [L,R=301,NC]



    Force www. version of domain to be used

    If you have a lot of links on the web where people are linking to your site as example.com, but you would like your visitors to instead end up at www.example.com you can force this version of your domain with these rules:
    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^example.com [NC]
    RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]



    Force non www. version of domain to be used

    If you have a lot of links on the web where people are linking to your site as www.example.com, but you would like your visitors to instead end up at example.com you can force this version of your domain with these rules:
    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^www.example.com [NC]
    RewriteRule ^(.*)$ http://example.com/$1 [L,R=301,NC]



    Redirect all files with certain extension

    To re-direct all of one type of file to another, such as example.com/file.php to example.com/file.htm
    RewriteEngine On
    RewriteCond %{REQUEST_URI} .php$
    RewriteRule ^(.*).php$ /$1.htm [R=301,L]



    Redirecting HTTP to HTTPS

    RewriteEngine On
    RewriteCond %{HTTPS} !on$
    RewriteRule ^(.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


    Redirect example.com to www.example.com:

    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]
    RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]



    Redirect www.example.com to example.com:

    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^www¥.example¥.com$
    RewriteRule ^/?$ "http¥:¥/¥/example¥.com¥/" [R=301,L]



    Redirect to example.com/index.php

    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^example.com$
    RewriteRule ^$ http://example.com/index.php [L,R=301]



    How to add a trailing slash

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !example.php
    RewriteCond %{REQUEST_URI} !(.*)/$
    RewriteRule ^(.*)$ http://example.com/$1/ [L,R=301]



    Removing Extensions such as .php, .html, .htm etc.

    To remove the .php extension from a PHP file for example gmaxlifesciences.com/index.php to gmaxlifescineces.com/index you have to add the following code inside the .htaccess file:

    Options +FollowSymLinks -MultiViews
    # Turn mod_rewrite on
    RewriteEngine On
    RewriteBase /

    ## hide .php extension
    ## To externally redirect /dir/foo.php to /dir/foo

    RewriteCond %{THE_REQUEST} ^[A-Z]{3,}¥s([^.]+)¥.php [NC]
    RewriteRule ^ %1 [R,L,NC]

    ## To internally redirect /dir/foo to /dir/foo.php

    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^ %{REQUEST_URI}.php [L]



    If you want to remove the .html extension from a html file for example gmaxlifesciences.com/index.html to gmaxlifesciences.com/index you simply have to alter the last line from the code above to match the filename:
    RewriteRule ^([^¥.]+)$ $1.html [NC,L]


    You can now link pages inside the HTML document without needing to add the extension of the page. For example:
    <a href="http://gmaxlifesciences.com/index" title="wallpaper">wallpaper</a>



    Adding a trailing slash at the end



    Note :-

    Attention GoDaddy users: In order to remove the extensions you need to enable MultiViews before. The code should look like this:
    Options +MultiViews
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^¥.]+)$ $1.php [NC,L]



    Remove user.php?id=31

    RewriteEngine on
    RewriteRule ^(.*) $1 [L]
    RewriteRule ^products/$ products.php?id=31 [L]



    For More Details : Click on link.


    To prevent the directory access of server files using htaccess.


    Options -Indexes


    To prevent the directory access of server files using htaccess. sucs images of your folder. So if any try to access your server like domainname.com/images/ or js/ etc. , it shows 403 error.

    write this line in your htaccess file.
    1. Options +Indexes
    2. Options -Indexes

    To prevent listing '.zip' files, create a .htaccess file following the main instructions and guidance which includes the following text:
    IndexIgnore *.zip

    To prevent listing multiple file types, create a .htaccess file following the main instructions and guidance which includes the following text:
    IndexIgnore *.zip *.jpg *.gif

    OR

    # the following prevents display of the filetohide file
    <files filetohide.jpg>
    order allow,deny
    deny from all
    </files>



    Redirect domain according to country IP address using php | .htaccess

    First you need to check that you have the mod_geoip module (GeoIP Extension) installed and configured on your server, If yes then tweak your .htaccess file accordingly..

    GeoIPEnable On
    GeoIPDBFile /path/to/GeoIP.dat

    # Start Redirecting countries

    # Australia
    RewriteEngine on
    RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^CA$
    RewriteRule ^(.*)$ http://au.example.com$1 [L]

    # USA
    RewriteEngine on
    RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^IN$
    RewriteRule ^(.*)$ http://us.example.com$1 [L]

    # India
    RewriteEngine on
    RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^IN$
    RewriteRule ^(.*)$ http://in.example.com$1 [L]


    By PHP

    First of all download geoplugin library and call it on your page.
    http://www.geoplugin.com/_media/webservices/geoplugin.class.phps

    require_once('geoplugin.class.php');
    $geoplugin = new geoPlugin();
    $geoplugin->locate();
    $countryCode = $geoplugin->countryCode;
    switch($countryCode) {
    case AU:
    header('Location: http://au.example.com/');
    break;
    case US:
    header('Location: http://us.example.com/');
    break;
    case IN:
    header('Location: http://in.example.com/');
    break;
    }
    ?>


    How to Block IP Address from accessing your website using .htaccess

    To block certain ip address from accessing your website.

    order allow,deny
    deny from 192.168.0.100
    allow from all

    If you want to block multiple ip address then follow below commands.

    order allow,deny
    deny from 192.168.0.100
    deny from 192.168.0.101
    deny from 192.168.0.102
    deny from 192.168.0.103
    allow from all

    You can also block certain network range like 192.168.0.0 – 192.168.0.199

    order allow,deny
    deny from 192.168.0
    allow from all


    To block all access to your site

    order allow,deny
    Deny from all


    And then add another line to enable access only for particular ip

    order allow,deny
    Deny from all
    Allow from 192.168.0.100

    Password protection

    File Name :

    AuthName "Admin Area"
    AuthUserFile /path/to/password/file/.htpasswd
    AuthType Basic
    require valid-user

    The first line tells the Apache Web Server the secure directory is called 'Admin Area', this will be displayed when the pop-up login prompt appears. The subsequent line indicates the location of the password file. The third line determines the authentication type, in this example, we are using 'Basic' because we are using basic HTTP authentication lastly the fourth line indicates that we require valid login credentials

    Adding MIME types

    File Name :

    AddType text/html htm0


    Itechtuto

    Connect Us Socially:

    Quick Links

    • itech
    • About Us
    • Feedback
    • Trademarks
    • Privacy Policy
    • Terms of Use
    • Sitemap
    • Trademarks
    • Privacy Policy
    • Terms of Use
    • Sitemap

    Copyright © 2016 itechxpert (P) Ltd. All rights reserved.

    Copyright © 2016 itechxpert (P) Ltd. All rights reserved.