Skip to content

Instantly share code, notes, and snippets.

@junaidtk
Last active July 9, 2018 17:43
Show Gist options
  • Save junaidtk/1e364200fa8a89d70e8db38ac47c3b56 to your computer and use it in GitHub Desktop.
Save junaidtk/1e364200fa8a89d70e8db38ac47c3b56 to your computer and use it in GitHub Desktop.
How to configure htaccess file
Htaccess file is used to redirect the url rewriting and also for making the SEO friendly URL.
Commomly used htaccess codes are listed below.
RewriteEngine on # This is to make the rewrite engin ON
RewriteCond and RewriteRule: => are the commonly used commands to write the htaccess codes.
"RewriteRule" :- It will redirect the current url to the required url.
"RewriteRule ^test/?$ test.php [NC,L] " # it will redirect to the test to the test.php
"RewriteCond" :- Rewrite condition check the condition and execute the next RewriteRule
Both "RewriteRule" and "RewriteCond" has two part in the commmand.
The first part defines how the orginal url looks like and
Second part defines how the new Url looks like.
Example for the Htaccess redirecting::
=============================================================
#(1) For redirecting url with 'www' as
RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain\.com [NC] # check the request url which is starting without "www"
RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301] # Root the Url to new url starting with "www"
#(2) Redirect old Url to new Url
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !oldexample.com$ [NC]
RewriteRule ^(.*)$ http://newexample.com/$1 [L,R=301]
L :=> last - stop processing rules
NC:=> case insensitive
R :=> temporary redirect to new URL
R :=> 301 (permanent redirect to new URL)
-d :=> (is test string a valid directory)
-f :=> (is test string a valid file)
[0-9]+ :=> one or more digits
^(.*)$ :=> contains the requested url, without the domain.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
means that if the file with the specified name in the browser doesn't exist,
or the directory in the browser doesn't exist then procede to the rewrite rule below smile
Some basic reqular expression charactres
==================================================
. (any character)
* (zero of more of the preceding)
+ (one or more of the preceding)
{} (minimum to maximum quantifier)
? (ungreedy modifier)
! (at start of string means "negative pattern")
^ (start of string, or "negative" if at the start of a range)
$ (end of string)
[] (match any of contents)
- (range if used between square brackets)
() (group, backreferenced group)
| (alternative, or)
\ (the escape character itself)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment