Using htaccess with PHP

Htaccess; Many useful referral jobs in the web area  It is an effective and multi-purpose settings file on Apache web servers that allows you to do this. It is one of my favorite events in this field, which helps us organize your web projects in many ways, create user-friendly URLs, and take security measures in a number of ways.

What can we do with Htaccess?

Ability to create SEO-friendly URLs. Subdomain or directory redirects such as site.com/icerik-title instead of site.com/icerik.php?id=123.site. Ability to redirect all error pages such as "404 page not found" to the desired location, such as redirecting to www.site.com when com is entered.

When site.com/non-page-asdasd is entered, a page of your choice can be opened.

You can ensure that only a certain IP can access your entire site or a directory.

While your site is under construction, only you can enter it and direct others to the under construction page.

Preventing access to private directories. You can prevent users from accessing a folder containing only included php files.

You can prevent some web service bots from crawling your site.

You can prevent a web search engine you do not like or a spam web service from crawling your site. .

You can encrypt your private directories.

Instead of trying to write a directory control system with PHP, you can use a few lines of htaccess command to enter the directory you want with a password.

Your images can be accessed elsewhere. You can prevent it from appearing on other sites.

By preventing the images on your site from being displayed on other sites, you can prevent your server's bandwidth from being consumed by other sites.

And apart from the ones listed above, you can do much more by using these methods together.

p>

Let's now take a look at how to do the things I mentioned above.

Creating SEO and user-friendly links

This is one of the most popular areas of use of Htaccess. And I believe it will be one of your favorite features. There are 2 ideal ways to use this event; The first is to use it with the GET method we learned before, in the form of page.php?page=contact, or with “REQUEST_URI” like the POST method. You can choose whichever is easier for you, but my favorite is “REQUEST_URI”. Method

1: Using the GET method. First, let's have a content page.php and define the pages with the switch for example purposes:


if(!isset($_GET['page'])) { // if empty, assume homepage. 
$page = 'homepage';
} else {
$page = $_GET['page'];
} switch($page) {
case 'contact': echo  'Contact';
echo 'Contact us at bilgi@site.com!';
echo 'Home Page';
break;case 'about':
echo 'About';
echo 'Those who know us know us, those who are new to us take an example, those who don't know us take a lesson.';
echo 'Home Page';
break;case 'homepage':
echo 'Welcome to our site!';
echo 'About';
echo 'Contact';
break;default: // if none, assume 404 
echo 'Not Found!';
echo 'We do not have such a page yet, it may have been changed or deleted.';
}

Currently, we can use this page as “page.php, page.php?page=about, page.php?page=contact” without using htaccess. Now let's make this user-friendly, we don't need to change anything in our code in this part. We create a file named ".htaccess" in the main directory of our site. If your FTP program or operating system does not allow you to create such a file, noteYou can open a blank page, write the codes in it, click save as, select the “All files” option and type “.htaccess” to create this file.

We write the following lines in it:


RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ page.php?page=$1  [QSA,L]

After doing this, Htaccess; If users try to enter a page that does not exist, that is, since we do not normally have a directory such as /about or /contact, it will redirect them to our page.php file, not to the 404 error page. However, when redirecting, we send the entered page to our file as the "page" GET parameter. In other words, when site.com/deneme is entered, the page that will run in the background will be "site.com/sayfa.php?sayfa=deneme". As a result, although the same system works, users no longer need to type the name of the php files or other GET parameter extensions. You can navigate your site with clean and catchy links.

Method 2: Doing it with REQUEST_URI.

The only difference from the other method is to use the address entered instead of $_GET['page'] with $_SERVER['REQUEST_URI'] We read with. But here it also gives us the initial “/” sign (as “/about”). To do this, we skip the first character with the substr function. In other words, we will change the first 5 lines of our code as follows:


$page = substr($_SERVER['REQUEST_URI'] , 1); // we skip the first "/" character.
if(!empty($page)) { // if it is empty, assume it is the homepage. $page = 'homepage';}
We make a one-line change in our .htaccess file for this method, deleting the part where we define the GET parameter:

RewriteRule ^(.*)$ page.php?page=$1  [QSA,L]// instead
RewriteRule ^(.*)$ page.php [L]
Subdomain or directory redirection

You can see an example on this blog; When you try to enter phpr.org, it automatically redirects you to www.phpr.org.  Although the issue here depends on the person's taste, it is more related to search engines. In some cases, Google may treat your site with and without the "www" suffix as two different sites. For example, when the link of your site is shared in many places both with and without "www", it partially distributes the popularity of the domain. When entered without "www" with htaccess, permanent redirection is made by adding it, all the attention is collected in a single subdomain and domain.


RewriteEngine OnRewriteCond %{HTTP_HOST} phpr.org [nc]RewriteRule (.*) //www.phpr.org/$1 [R= 301,L]
You can also do the opposite if you want;
RewriteEngine OnRewriteCond %{HTTP_HOST} www.phpr.org [nc]RewriteRule (.*) http://phpr.org/$1 [ R=301,L]
We can also redirect a directory very simply with a single line. The point to consider is how will you direct the directory? Generally, permanent (301) or temporary (302) states are used. You can look here for more. If you say permanent redirect (301), search engines will replace the indexes in the entered address with the newly redirected address. If you say temporary, it will enter and scan the forwarded address without making any changes.

RewriteEngine OnRewriteRule ^old_adres$ /new_adres [R=301,L]
Redirect error pages You can look here to find out the status codes of the error pages. The most common of these we know are; Page not found with code 404, another example is page error code 403 with no login permission. AttentionThe point you need to make is; Since the basis of the SEO and user-friendly link creation method above is to redirect non-existent pages, that is, pages with 404 codes, to our specific file, it will be useless to try to define a 404 page with the following codes while using that method.

ErrorDocument 403 /no_permission.html
ErrorDocument 404 /not found.html
Allow/block specific IP address You can block IP access for an entire site or just specific folders if you wish. To do this, simply place the “.htaccess” file you prepared into the relevant subfolder.

deny from all //block everyone from entering
allow from 127.0.0.1 //allow this ip address
allow from 192.168.0.0/255 //or allow this ip block
Blocking access of some bots and web services With a simple htaccess move, you can block bots that you do not want, or bots that are tiring by wandering around your site excessively, and relieve your server. You can find the list of all bots that are generally marked as malicious, for this method, at this address. I will write a few of them for example purposes.

RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} ^WebWhacker [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebZIP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Wget [OR]
RewriteCond %{HTTP_USER_AGENT} ^Widow [OR]
RewriteCond %{HTTP_USER_AGENT} ^WWWOFFLE [OR]
RewriteCond %{HTTP_USER_AGENT} ^Xaldon WebSpider [OR]
RewriteRule .* - [F]
You can also use this method to detect people entering from mobile devices and direct them to your mobile site.

RewriteCond %{REQUEST_URI} !^/mobil_dizin/.*$
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
RewriteRule ^(.*)$ /mobil_dizin/ [L,R= 302]
Encrypting private directories For this method, we first need to create a simple password file. We can add one user per line in the file. And in each line, we define the username and password as "name:password". We name our password file as .htpasswd and place it in a specified place in our .htaccess file. Then, with this information, we write the following into the directory we want to encrypt.

AuthUserFile /file/directory/.htpasswd
AuthType Basic
AuthName "Secret Directory"
Preventing content from being used on other sites This method, known as Hotlink, allows you to prevent content such as music, pictures and videos on your site from being displayed and played on other sites. In this way, you prevent your server's bandwidth from being wasted on other sites. In this method, when an image from another site is requested to be displayed, we can show a hotlink warning image instead of the desired image. You've probably seen many examples of this on imageshack.us.

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://([-a-z0-9]+.)?yazilimpark.com.tr [NC]
RewriteRule .*.(zip|mp3|avi< span class="keyword operator">|wmv|mpg|mpeg)$ //www.yazilimpark.com.tr/hotlinkresim.jpg [R,NC,L]
Some details to pay attention to If you noticed, almost all of the methods I showed above have the first “RewriteEngine on” command. If you are going to use several of these methods together, you do not need to add this line repeatedly. Just do this with htaccess fileIt is enough to write it once at the beginning of your file. Another important point is that when using more than one command, remember that the order of the operations is important. So, if you first write the 404 error page warning command and write SEO-friendly link commands on the bottom line, the SEO-friendly link method will not work because the 404 error page command will be triggered first and go to the relevant place. The meanings of the letters NC, L and R used in parentheses are:

L: The rules expressed before LastBu are defined ensure that they do not pass on or interfere with the following ones.

R: Redirect If this value is used, the address changes in the browser. If not, the redirection is done in the background, but the URL entered by the user remains the same.

NC: No Case It is case insensitive.

QSA: When we redirect with the Query String AppendGET method, the   It also includes GET parameters.