PHP 247
September 09, 2010, 01:29:16 PM *
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
 

Pages: [1]
Print
Author Topic: .htaccess useage  (Read 333 times)
cmxq
Administrator
Sr. Member
*****
Posts: 365

Thank You
-Given: 0
-Receive: 0


View Profile WWW
« on: February 27, 2010, 02:35:23 AM »

(From KenyLieou-phpvn.org)

All tutorials about Htaccess

+ Block unwanted referrers from you website

Code:
RewriteEngine on
RewriteCond %{HTTP_REFERER} digg.com [NC]
RewriteRule .* - [F]

description: this will block digg.com

+ Block some Ips

Code:
<limit get="" post="" put="">
order deny,allow
deny from 210.245.11.12
allow from all
</limit>

Description: this will block ip 210.245.11.12 (for i.e) , and you can block many Ips as you like, just separate by a comma ","

That is very simple. Why don't you try it.

+ Using htaccess to protect a directory

this require 2 file - .htaccess and .htpasswd

File .htaccess:
Code:
AuthType Basic
AuthName "restricted area"
AuthUserFile /home/davidwalsh/html/protect-me-dir/.htpasswd
require valid-user

File .htpasswd
Code:
keny:daWHfZrDLB88.
lieou:roFulYxC2.8ws

you can add many user you want by user:pass perline
use crypt (php function) to create htpasswd



Logged

http://www.eabeauty.net - The world of beauty and cute girls !!!
http://www.newgamesonline.net -  Free flash games online !!!
cmxq
Administrator
Sr. Member
*****
Posts: 365

Thank You
-Given: 0
-Receive: 0


View Profile WWW
« Reply #1 on: February 27, 2010, 02:36:44 AM »

Okie, let me go on with Apache Mod_rewrite
this is a useful module supported by apache,
It gives you the ability to transparently redirect one URL to another, without the user’s knowledge. This opens up all sorts of possibilities, from simply redirecting old URLs to new addresses, to cleaning up the ‘dirty’ URLs coming from a poor publishing system — giving you URLs that are friendlier to both readers and search engines.that mean redirect some to another

Before you use, you must turn it on, because some server will not have mod_rewrite enabled by default
Syntax:
Code:
RewriteEngine on

Mod_rewrite syntax:
Quote
RewriteRule url-pattern url-new [[flag,...]]
#Example: RewriteRule ^/foo/(.*)$ /bar/$1 [R,L]
#Since: Apache 1.2

This directive is the real rewriting workhorse. It can occur more than once. Each directive then defines a single rewriting rule. The definition order of these rules is important, because it is used when applying the rules at runtime.
+The url-pattern is a regular expression that is applied to the current URL
+The url-new argument is the string that is substituted for the original URL matched by the url-pattern.
+In addition, you can set special flags for url-new by appending one or more flag arguments.

Rewrite Rule (for url-pattern)
Quote
Text:
  .           Any single character
  [chars]     Character class: One  of chars
  [^chars]    Character class: None of chars
  text1|text2 Alternative: text1 or text2

Quantifiers:
  ?           0 or 1 of the preceding text
  *           0 or N of the preceding text (N > 0)
  +           1 or N of the preceding text (N > 1)

Grouping:
  (text)      Grouping of text
              (either to set the borders of an alternative or
              for making backreferences where the Nth group can
              be used on the RHS of a RewriteRule with $N)

Anchors:
  ^           Start of line anchor
  $           End   of line anchor

Escaping:
  \char       escape that particular char
              (for instance to specify the chars ".[]()" etc.)

Flag:
- redirect (or R) to force an HTTP redirect;
- forbidden (or F) to forbid access;
- gone (or G) to eliminate the URL;
- proxy (or P) to pass the URL to mod_proxy;
- last (or L) to stop processing;
- next (or N) to start the next round of processing;
- chain (or C) to chain the current rule with the following one;
- type (or T) to force a particular MIME type;
- nosubreq (or NS) to ensure that the rule applies only if no internal sub-request is performed;
- nocase (or NC) to force the URL matching to be case-insensitive;
- qsappend (or QSA) to append a query string part in url-new to the existing one instead of replacing it;
- passthrough (or PT) to pass the rewritten URL through to other Apache modules;
- skip (or S) to skip the next rule;
- env (or E) to set an environment variable.

Basic Rewrite:
Code:
RewriteEngine on
RewriteRule ^old\.html$ new.html


So, this rule will make your server transparently redirect from old.html to the new.html page. Your reader will have no idea that it happened, and it’s pretty much instantaneous.

Forcing New Requests by Using Flags
Code:
RewriteEngine on
RewriteRule ^old\.html$ new.html [[b]R[/b]]


This will make the browser load up the new page as if it was the page originally requested
More example:
Code:
RewriteEngine on
RewriteRule ^/?test\.html$ test.php [L]
when you go to http://yourdomain/path/folder/test.html, you will see the content of test.php file

Regular Expressions In Rewrite
Some URL like : http://www.example.com/display.php?country=USA&state=California&city=San_Diego
Yes Our problem is that this is way too long an unfriendly to users. We'd much prefer it if visitors could use:
http://www.example.com/USA/California/San_Diego

How can we do dat ?
The Answer is using mod_rewrite and regular expression
Code:
RewriteRule ^/?([a-zA-Z_]+)/([a-zA-Z_]+)/([a-zA-Z_]+)$ display.php?country=$1&state=$2&city=$3 [L]

Code:
^/?([a-zA-Z_]+)/([a-zA-Z_]+)/([a-zA-Z_]+)$

to
Code:
display.php?country=$1&state=$2&city=$3

The RewriteCond Statement
Now that you've learned how to use mod_rewrite's basic RewriteRule statement with the {REQUEST_URI} string, it's time to see how we can use conditionals to access other variables with the RewriteCond statement. The RewriteCond statement is used to specify the conditions under which a RewriteRule statement should be applied.

RewriteCond is similar in format to RewriteRule in that you have the command name, RewriteCond, a variable to be matched, the regex, and flags. The logical OR flag, [OR], is a useful flag to remember because all RewriteCond and RewriteRule statements are inclusive, in the sense of a logical AND relationship, until terminated by the Last, [L], flag.

You can test many server variables with a RewriteCond statement. You can find a list in the SitePoint article I mentioned previously, but this is the best list of server variables I've found:
http://vn2.php.net/reserved.variables#reserved.variables.server

As an example, let's assume that we want to force the www in your domain name. To do this, you'll need to test the Apache {HTTP_HOST} variable to see if the www. is already there and, if it's not, redirect to the desired host name:

Code:
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule .? http://www.example.com%{REQUEST_URI} [R=301,L]

Here, to denote that {HTTP_HOST} is an Apache variable, we must prepend a % character to it. The regex begins with the ! character, which will cause the condition to be true if it doesn't match the pattern. We also have to escape the dot character so that it matches a literal dot and not any character, as is the case with the dot metacharacter. We've also added the No Case flag to make this operation case-insensitive.

The RewriteRule will match zero or one of any character, and will redirect to http://www.example.com plus the original {REQUEST_URI} value. The R=301, or redirect, flag will cause Apache to issue a HTTP 301 response, which indicates that this is a permanent redirection; the Last flag tells mod_rewrite that you've completed this block statement.

RewriteCond statements can also create atoms, but these are denoted with %1 ... %9 in the same way that RewriteRule atoms are denoted with $1 ... $9. You'll see these atom variables in operation in the examples later on.

mod_rewrite Comments
it simply like PHP /* .. */ :p


Logged

http://www.eabeauty.net - The world of beauty and cute girls !!!
http://www.newgamesonline.net -  Free flash games online !!!
cmxq
Administrator
Sr. Member
*****
Posts: 365

Thank You
-Given: 0
-Receive: 0


View Profile WWW
« Reply #2 on: February 27, 2010, 02:37:05 AM »

13 mod_rewrite Examples

Earlier, we looked at an example that forced the inclusion of the www part of a domain name for every request. Let's have a look at some more examples and see how useful mod_rewrite can be.

1. Forcing www for a domain while preserving subdomains

Code:
RewriteCond %{HTTP_HOST} ^([a-z.]+)?example\.com$ [NC]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .? http://www.%1example.com%{REQUEST_URI} [R=301,L]

This rule captures the optional subdomain using the %1 variable, and, if it doesn't start with www., redirects with www. prepended to the subdomain. The domain and the original {REQUEST_URI} are appended to the result.

2. Eliminating www from a domain

Code:
RewriteCond %{HTTP_HOST} !^example\.com$ [NC]
RewriteRule .? http://example.com%{REQUEST_URI} [R=301,L]

3. Getting rid of the www but preserving a subdomain

Code:
RewriteCond %{HTTP_HOST} ^www\.(([a-z0-9_]+\.)?example\.com)$ [NC]
RewriteRule .? http://%1%{REQUEST_URI} [R=301,L]

Here, the subdomain is captured in %2 (the inner atom) but, since it's optional and already captured in the %1 variable, all you need is the %1 for the subdomain.

4. Preventing image hotlinking

If some unscrupulous webmasters are leeching your bandwidth by linking to images from your site to post on theirs, you can use the following rule to block the requests:

Code:
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?example\.com/ [NC]
RewriteRule \.(gif|jpg|png)$ - [F]

If the {HTTP_REFERER} value is not blank, or from your own domain (example.com), this rule will block the viewing of URIs ending in .gif, .jpg, or .png using the forbidden flag, F.

If you are upset enough at these hotlinkers, you could change the image and let visitors to the site know that you know that they're hotlinking:

Code:
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?example\.com/.*$ [NC]
RewriteRule \.(gif|jpg|png)$ http://www.example.com/hotlinked.gif [R=301,L]

Instead of blocking the URI, the above rule rewrites it to a specific image in our domain. What appears in this image is completely up to your imagination!

You can block specific domains using:

Code:
RewriteCond %{HTTP_REFERER} !^http://(www\.)?leech_site\.com/ [NC]
RewriteRule \.(gif|jpg|png)$ - [F,L]

This rule blocks all requests where the {HTTP_REFERER} field is set to the bad domain.

Of course, the above rules rely on the {HTTP_REFERER} value being set correctly. It usually is, but if you'd rather rely on the IP Address, use {REMOTE_ADDR} instead.

5. Redirecting to a 404 page if the directory and file do not exist

If your host doesn't provide for a "file not found" redirection, create it yourself!

Code:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .? /404.php [L]

Here, -f matches an existing filename and -d matches an existing directory name. This script checks to see that the requested filename is not an existing filename or directory name before it redirects to the 404.php script. You can extend this script: include the URI in a query string by adding ?url=$1 immediately after the URI:

Code:
RewriteRule ^/?(.*)$ /404.php?url=$1 [L]

This way, your 404.php script can do something with the requested URL: display it in a message, send it in an email alert, perform a search, and so on.

6. Renaming your directories

If you've shifted files around on your site, changing directory names, try this:

Code:
RewriteRule ^/?old_directory/([a-z/.]+)$ new_directory/$1 [R=301,L]

I've included the literal dot character (not the "any character" metacharacter) inside the set to allow file extensions.

7. Converting old .html links to new .php links

Updating your web site but need to be sure that bookmarked links will still work?

Code:
RewriteRule ^/?([a-z/]+)\.html$ $1.php [L]

This is not a redirection, so it will be invisible to your visitors. To make it permanent (and visible), change the flag to [R=301,L].

8. Creating extensionless links

If your site uses PHP files, and you want to make your links easier to remember -- or you just want to hide the file extension, try this:

Code:
RewriteRule ^/?([a-z]+)$ $1.php [L]

If you have a mixture of both .html and .php files, you can use RewriteCond statements to check whether the filename with either extension exists as a file:

Code:
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^/?([a-zA-Z0-9]+)$ $1.php [L]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^/?([a-zA-Z0-9]+)$ $1.html [L]

If the file name exists with the .php extension, that rule will be chosen.

9. Checking for a key in a query string

If you need to have a specific key's value in your query string, you can check for its existence with a RewriteCond statement:

Code:
RewriteCond %{QUERY_STRING} !uniquekey=
RewriteRule ^/?script_that_requires_uniquekey\.php$ other_script.php [QSA,L]

The above code will check the {QUERY_STRING} variable for a lack of the key uniquekey and, if the {REQUEST_URI} is the script_that_requires_uniquekey, it will redirect to an alternative URI.

10. Deleting the query string

Apache's mod_rewrite automatically passes through a query string unless you do either of the following:

    * Assign a new query string (you can keep the original query string by adding a QSA flag, e.g., [QSA,L]).
    * Add a ? after a filename (for example, index.php?). The ? will not be shown in the browser's location field.

11. Redirecting a working URI to a new format

Here's a curly one. Let's say, for example, that we've got a set of working URLs that look like this: /index.php?id=nnnn. However, we'd really like to change them to /nnnn and make sure search engines update their indexes to the new URI format. First, we'd have to redirect the old URIs to the new ones so that search engines update their indexes, but we'd still have to rewrite the new URI back to the old one so that the index.php script would run. Have I got your head spinning?

The trick here is to place into the query string a marker code that will not be seen by visitors. We redirect from the old link to the new format only if the "marker" is not present in the query string. Then we rewrite the new format link back to the old format, and add a marker to the query string, using the QSA flag to ensure we're not eliminating an existing query string. Here's how it's done:

Code:
RewriteCond %{QUERY_STRING} !marker
RewriteCond %{QUERY_STRING} id=([-a-zA-Z0-9_+]+)
RewriteRule ^/?index\.php$ %1? [R=301,L]

RewriteRule ^/?([-a-zA-Z0-9_+]+)$ index.php?marker&id=$1 [L]

Here, the original URI, http://www.example.com/index.php?id=nnnn, does not contain the marker, so it's redirected by the first rule to http://www.example.com/nnnn with a HTTP 301 response. The second rule rewrites http://www.example.com/nnnn back to http://www.example.com/index.php?marker&id=nnnn, adding marker and id=nnnn in a new query string; then, the mod_rewrite process is started over.

In the second iteration, the marker is matched so the first rule is ignored and, since there's a dot character in index.php?marker&id=nnnn, the second rule is also ignored ... and we're finished!

Note that, while useful, this solution does require additional processing by Apache, so be careful if you're using it on shared servers with a lot of traffic.

12. Ensuring that a secure server is used

Apache can determine whether you're using a secure server in two ways: using the {HTTPS}, or {SERVER_PORT}, variables:

Code:
RewriteCond %{REQUEST_URI} ^secure_page\.php$
RewriteCond %{HTTPS} !on 
RewriteRule ^/?(secure_page\.php)$ https://www.example.com/$1 [R=301,L]

The above example tests that the {REQUEST_URI} value is equal to our secure page script, and that the {HTTPS} value is not equal to on. If both these conditions re met, the request is redirected to the secure server URI. Alternatively, you could do the same thing by testing the {server_port} value, where 443 is typically the secure server port:

Code:
RewriteCond %{REQUEST_URI} ^secure_page\.php$
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^/?(secure_page\.php)$ https://www.example.com/$1 [R=301,L]

13. Enforcing secure server only on selected pages

In situations where secure and unsecured domains share the web server's DocumentRoot directory, you'll need a RewriteCond statement to check that the secure server port isn't being used, and then only redirect the request if the requested script is one in the list of those that require a secure server:

Code:
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^/?(page1|page2|page3|page4|page5)$  https://www.example.com/%1 [R=301,L]

Here's how you'd redirect requests for pages not requiring a secure server back to port 80:

Code:
RewriteCond %{ SERVER_PORT } ^443$ 
RewriteRule !^/?(page6|page7|page8|page9)$ http://www.example.com%{REQUEST_URI} [R=301,L]

Cheer,
Logged

http://www.eabeauty.net - The world of beauty and cute girls !!!
http://www.newgamesonline.net -  Free flash games online !!!
cmxq
Administrator
Sr. Member
*****
Posts: 365

Thank You
-Given: 0
-Receive: 0


View Profile WWW
« Reply #3 on: February 27, 2010, 02:37:38 AM »

Go on :p More Cheet sheet about htaccess

Enable Directory Browsing
Code:
Options +Indexes
## block a few types of files from showing
IndexIgnore *.wmv *.mp4 *.avi

Disable Directory Browsing
Code:
Options All -Indexes

Customize Error Messages
Code:
ErrorDocument 403 /forbidden.html
ErrorDocument 404 /notfound.html
ErrorDocument 500 /servererror.html

Get SSI working with HTML/SHTML
Code:
AddType text/html .html
AddType text/html .shtml
AddHandler server-parsed .html
AddHandler server-parsed .shtml
# AddHandler server-parsed .htm

Change Default Page (order is followed!)
Code:
DirectoryIndex myhome.htm index.htm index.php

Block Users from accessing the site
Code:
<limit GET POST PUT>
order deny,allow
deny from 202.54.122.33
deny from 8.70.44.53
deny from .spammers.com
allow from all
</limit>

Allow only LAN users
Code:
order deny,allow
deny from all
allow from 192.168.0.0/24

Redirect Visitors to New Page/Directory
Code:
Redirect oldpage.html http://www.domainname.com/newpage.html
Redirect /olddir http://www.domainname.com/newdir/

Block site from specific referrers
Code:
RewriteEngine on
RewriteCond %{HTTP_REFERER} site-to-block\.com [NC]
RewriteCond %{HTTP_REFERER} site-to-block-2\.com [NC]
RewriteRule .* - [F]

Stop .htaccess (or any other file) from being viewed
Code:
<files *.ht>
order allow,deny
deny from all
</files>

Avoid the 500 Error
Code:
# Avoid 500 error by passing charset
AddDefaultCharset utf-8

Grant CGI Access in a directory
Code:
Options +ExecCGI
AddHandler cgi-script cgi pl
# To enable all scripts in a directory use the following
# SetHandler cgi-script

Change Script Extensions
Code:
AddType application/x-httpd-php .kny

kny will now be treated as PHP files! Similarly, x-httpd-cgi for CGI files, etc.

Save Bandwidth
Code:
# Only if you use PHP
<ifmodule mod_php4.c>
php_value zlib.output_compression 16386
</ifmodule>

Turn off magic_quotes_gpc
Code:
# Only if you use PHP
<ifmodule mod_php4.c>
php_flag magic_quotes_gpc off
</ifmodule>
Hi a 5s: you are welcome Smiley

Cheer,
Logged

http://www.eabeauty.net - The world of beauty and cute girls !!!
http://www.newgamesonline.net -  Free flash games online !!!
Pages: [1]
Print
Jump to:  

Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC
Note, by Smoky