Showing posts with label htaccess. Show all posts
Showing posts with label htaccess. Show all posts

Wednesday 10 December 2014

Htaccess RewriteRule Flags by Code Example

Htaccess RewriteRule Flags by Code Example

A RewriteRule can be modified by flag. Flags are included in square brackets at the end of the rule. We can also and multiple flags are separated by commas.

For Example:
[Flag1] //for 1 flag
[Flag1,Flag2] //for 2 flags
[Flag1,Flag2,Flag3 ] //for multiple flags

Following are most commonly htaccess flag:
1. htacces B(escape backreferences) Flag
Escape non-alphanumeric characters before applying the transformation


2. htaccess C(Chain) Flag
First htaccess Rule will be applied to next htaccess rule. Means if the rule matches, then control moves on to the next rule.


3. htaccess CO(Cookie) Flag
you can set a cookie when a particular RewriteRule matches
RewriteRule ^search/(.*)$ /search.php?term=$1[CO=variable:variableValue]
Set the variable=variableValue in cookie


4. htaccess DPI(discardpath) Flag
PATH_INFO portion of the rewritten URI to be discarded.


5. htaccess E (env) Flag
You can set the value of an environment variable. For example:
RewriteRule ^search/(.*)$ /search.php?term=$1[E=variable:variableValue]
Set the variable=variableValue in environment variable.


6. htaccess END Flag
This flag terminates not only the current round of rewrite but also prevents any subsequent rewrite from occurring in per-directory.


7. htaccess F(forbidden) Flag
This flag causes the server to return a 403 Forbidden status code to the client. For Example
RewriteRule \.exe - [F]
If anyone trying to open any file with .exe, he will get Forbidden error.



8. htaccess G(gone) Flag
This flag causes the server to return a 410 Gone status with the response code to the client. For Example
RewriteRule old_url - [G]
If old_url called, 410 gone status will be shown in the browser.



9. htaccess H(handler) Flag
This flag causes Forces the request to be handled with the specified handler. For example
RewriteRule !\. - [H=application/x-httpd-php]
Force all files without a file extension to be parsed by the php handler.



10. htaccess L(Last) Flag
This flag causes to stop processing the rule set, if the rule matches, no further rules will be processed.
RewriteRule ^(.*) /index.php?req=$1 [L]



11. htaccess N(Next) Flag
This flag causes ruleset to start over again from the top.
RewriteRule ^(.*) /index.php?req=$1 [N]


12. htaccess NC(nocase) Flag
This flag causes RewriteRule to be matched in a case-insensitive manner.
RewriteRule ^(.*) /index.php?req=$1 [NC]



13. htaccess NE(noescape) Flag
By default, special characters, such as & and ?, are converted to their hexcode equivalent. By Using NE flag prevents we can prevent this.


14. htaccess NS(nosubreq) Flag
This flag causes prevents the rule from being used on subrequests.



15. htaccess P(proxy) Flag
This flag causes the request to be handled by proxy request. For example, if you wanted all image requests to be handled by a image server
RewriteRule /(.*)\.(jpg|gif|png)$ http://images.mysite.com/$1.$2 [P]
Extension having jpg, gif, and png will be handled by images.mysite.com



16. htaccess PT(passthrough) Flag
This flag causes the result of the RewriteRule to be passed back through URL mapping.



17. htaccess QSA(qsappend) Flag
When the replacement URI contains a query string, the default behavior of RewriteRule is to discard the existing query string, and replace it with the newly generated one. Using the [QSA] flag causes the query strings to be combined.

18. htaccess S(Skip) flag
htaccess S flag is used to skip rules that you don't want to run. The syntax of the skip flag is [S=N], where N means the number of rules to skip. For Example
# Does the file exist?
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Create an if-then-else construct by skipping 3 lines if we meant to go to the "else" stanza.
RewriteRule .? - [S=3]

# IF the file exists, then:
    RewriteRule (.*\.gif) images.php?$1
    RewriteRule (.*\.html) docs.php?$1
    # Skip past the "else" stanza.
    RewriteRule .? - [S=1]
# ELSE...
    RewriteRule (.*) 404.php?file=$1
# END


19. htaccess T(type) flag
htaccess T flag cause sets the MIME type with which the resulting response will be sent. For Example
RewriteRule IMG - [T=image/jpg]


20. htaccess R(Redirect) flag
htacces R flag causes a HTTP redirect to be issued to the browser. Normally Redirect does not occur but if we use R Flag, then redirection will be happened to the browser. For Example
RewriteRule (.*\.gif) images.php?$1 [R]

Saturday 22 February 2014

htaccess code snippets example

htaccess code snippets example

.htaccess file is used for configuration on File Level/Directory Level and its supported by all webserver. Today all types of websites use htaccess technology.



Following are Benefits of .htaccess
  • Mange Error Pages for Better SEO
  • Set PHP Config variable
  • Set Environment variable
  • Password protection for File/Directory
  • Allow/Deny visitors by IP Address
  • Detect OS (like Mobile/Laptop/Ios/Android)
  • Redirection pages 
  • Optimize Performance of website
  • Improve Site Security


Following are Few Example of .htaccess

Redirect Home page to Another Website
Redirect / http://php-tutorial-php.blogspot.in/


Redirect Home page to Another another Directory(i.e newdir)
Redirect / /newdir


Redirect about.html to Another another Directory(i.e /pages/about)
Redirect /about.html /pages/about


Redirect old file to New Path
Redirect /oldfile.html /newfile.html


Set PHP Environment
SetEnv APPLICATION_ENV development


Set max_filesize in php
php_value upload_max_filesize 32M


Set off error in PHP
php_flag display_errors off
php_flag display_startup_errors off


Dedect mobile/laptop and redirect to mobile site
RewriteCond %{HTTP_USER_AGENT} android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|ipad|ipod|iemobile|ip(hone|od)|iris|kindle|lge\ |maemo|midp|mmp|opera\ m(ob|in)i|palm(\ os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows\ (ce|phone)|xda|xiino [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^(1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a\ wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r\ |s\ )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1\ u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp(\ i|ip)|hs\-c|ht(c(\-|\ |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac(\ |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt(\ |\/)|klon|kpt\ |kwc\-|kyo(c|k)|le(no|xi)|lg(\ g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-|\ |o|v)|zz)|mt(50|p1|v\ )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v\ )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-|\ )|webc|whit|wi(g\ |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-) [NC]
RewriteRule ^$ http://mobile.domain.com/ [R,L]


Block IP Address
order allow,deny
deny from xxx.xxx.xxx.xxx #specify a specific address
deny from xxx.xxx.xxx.xxx/30 #specify a subnet range
deny from xxx.xxx.* #specify an IP address wildcard
allow from all


Allow IP Address
order allow,deny
allow from xxx.xxx.xxx.xxx #specify a specific address
allow from xxx.xxx.xxx.xxx/30 #specify a subnet range
allow from xxx.xxx.* #specify an IP address wildcard
allow from all


Redirect to 400.html, If 400 error comes
ErrorDocument 400 /errorpages/400.html


Redirect to 403.html, If 403 error comes
ErrorDocument 403 /errorpages/403.html


Redirect to 404.html, If 404 error comes
ErrorDocument 404 /errorpages/404.html


Redirect to 500.html, If 500 error comes
ErrorDocument 500 /errorpages/500.html


Disable Directory Listing
Options ExecCGI Includes IncludesNOEXEC SymLinksIfOwnerMatch -Indexes


Enable Directory Listing
 Options All +Indexes


Password Protection
AuthName "Authentication Section"
AuthType Basic
AuthUserFile /home/username/.htpasswds #Here your password will be stored
#htpasswds file format username:password
Require valid-user


Password Protection but Google can Crawl
AuthName "Under Development"
AuthUserFile /home/website/.htpasswd
AuthType basic
Require valid-user
Order deny,allow
Deny from all
Allow from xxx.xxx.xxx.xxx w3.org htmlhelp.com googlebot.com
Satisfy Any


Set Timezone of the Server
SetEnv TZ America/Indianapolis


301 Redirect Old File
Redirect 301 /old/file.html http://php-tutorial-php.blogspot.in/2013/12/curl-example.html


301 Redirect Entire Directory
Redirect 301 /old/ /new/



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


301 redirect https to http://www
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


301 redirect non www to www with htaccess
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]


Set Caching for javascript/image/css
ExpiresActive On
ExpiresByType application/javascript "now plus 3 day"
ExpiresByType application/x-javascript "now plus 3 day"
ExpiresByType image/jpg "now plus 1 week"
ExpiresByType image/jpeg "now plus 1 week"
ExpiresByType image/png "now plus 1 week"
ExpiresByType image/pjpeg "now plus 1 week"
ExpiresByType image/gif "now plus 1 week"
ExpiresByType text/css "now plus 3 day"


Error Codes - Defination
301 - Permanent movement(redirection)
302 - Temporary movement(redirection)
400 - Bad request
401 - Authorization Required
403 - Forbidden
404 - Page Not Found
500 - Internal Server Error