8. PHP Tutorial - HTAccess - URL Rewriting

PHP Tutorial – HTAccess – URL Rewriting

()

What is HTAccess?

HTAccess is a configuration file used by the Apache web server to allow users to set rules for accessing content on their website. It is a powerful tool that allows users to define custom error pages, password-protect directories, and redirect traffic to different pages or servers. HTAccess can be used to improve website security, SEO, and user experience.

.htaccess is a configuration file used by the Apache web server software. It allows you to specify certain configurations for the server to follow when serving your website to visitors. You can use .htaccess to configure things like redirects, password protection, and other settings. The file is usually located in the root directory of your website, and the configurations specified in the file apply to that directory and all subdirectories underneath it.

Example of HTAccess file:

Here is an example of an HTAccess file that can be used to password-protect a directory on a website:

Protect directory with basic authentication:

AuthType Basic
AuthName "Restricted Area"
AuthUserFile /path/to/htpasswd
Require valid-user

This HTAccess file tells the Apache web server to use basic authentication to protect the directory. The “AuthName” field specifies the name that will be displayed on the login prompt, and the “AuthUserFile” field points to the location of the htpasswd file that contains the username and password information for users who are allowed access to the protected directory. The “Require valid-user” directive ensures that only users with valid credentials are allowed access.

What is URL Rewriting?

URL rewriting is the process of modifying the appearance of a website’s URL in order to make it more user-friendly or search engine friendly. This can be done using the HTAccess file or other server-side programming languages such as PHP or ASP.NET.

For example, a website may have a URL that looks like this: “http://www.example.com/index.php?id=123“. This URL may be rewritten to look like this: “http://www.example.com/articles/article-title“. The rewritten URL is easier for users to read and understand, and it is also more search engine friendly as it includes relevant keywords in the URL.

URL rewriting can be used to improve the user experience, SEO, and security of a website. It can also be used to redirect traffic to different pages or servers, or to hide the actual location of a webpage.

URL Rewriting in .htaccess file for Apache Server:

Here is an example of how URL rewriting can be done using the HTAccess file on an Apache web server:

Enable mod_rewrite:

RewriteEngine On

Rewrite /articles/article-title to /index.php?id=123:

RewriteRule ^articles/article-title$ /index.php?id=123 [L]

This HTAccess file enables the mod_rewrite module, which allows for URL rewriting on the Apache web server. The RewriteRule directive specifies a pattern to match and a corresponding substitution to be made if the pattern is matched. In this case, if a user accesses the URL “http://www.example.com/articles/article-title“, the Apache web server will internally rewrite the URL to “http://www.example.com/index.php?id=123” and serve the corresponding content. The [L] flag indicates that this is the last rule to be applied, so no further rewriting will be done.

In which servers can we use .htaccess file?

The HTAccess file can be used on servers that use the Apache web server software, such as:

  • XAMPP
  • WampServer
  • MAMP
  • LAMP
  • Apache HTTP Server

These servers are often used for local development environments, such as for testing and debugging web applications. The HTAccess file can be used to configure the Apache web server and set rules for accessing content on the website.

Various Advanced .htaccess commands:

Here are some advanced .htaccess commands that can be used to customize and optimize a website:

  1. Redirecting traffic:
  • Redirect all traffic to a new domain:
Redirect permanent / http://www.newdomain.com/
  • Redirect a specific URL to a new URL:
Redirect 301 /old-url/ http://www.example.com/new-url/
  1. Improving security:
  • Block access to specific IP addresses:
Deny from 123.456.789.0/24
  • Require a password to access a specific directory:
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /path/to/htpasswd
Require valid-user
  1. Customizing error pages:
  • Set a custom 404 error page:
ErrorDocument 404 /404.html
  • Set a custom 500 error page:
ErrorDocument 500 /500.html
  1. Enhancing SEO:
  • Set a custom page title for a specific URL:
Header add Title "Custom Page Title"
  • Set the X-Robots-Tag header to block search engines from indexing a specific URL:
Header set X-Robots-Tag "noindex, nofollow"
  1. Compressing content:
  • Enable Gzip compression for text, html, and css files:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/css
  1. Caching content:
  • Set the cache expiration time for static resources:
<FilesMatch ".(css|jpg|jpeg|png|gif|js)$">
    Header set Cache-Control "max-age=2592000"
</FilesMatch>

Can we use .htaccess file in IIS Server for PHP?

The HTAccess file is specific to the Apache web server and cannot be used on servers that use other software, such as the IIS web server. However, similar functionality can be achieved on IIS servers using the web.config file and URL rewriting rules.

For example, to enable URL rewriting on an IIS server for a PHP website, you can use the following configuration in the web.config file:

<system.webServer>
    <rewrite>
        <rules>
            <rule name="Rewrite to index.php" stopProcessing="true">
                <match url="^articles/article-title$" />
                <action type="Rewrite" url="/index.php?id=123" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

This configuration tells the IIS web server to rewrite the URL “http://www.example.com/articles/article-title” to “http://www.example.com/index.php?id=123” and serve the corresponding content. The PHP handler can also be specified in the web.config file using the following configuration:

<system.webServer>
    <handlers>
        <add name="PHP" path="*.php" verb="*" modules="FastCgiModule" scriptProcessor="C:\php\php-cgi.exe" />
    </handlers>
</system.webServer>

To convert an HTAccess file to a web.config file, you can use a tool such as the HTAccess to web.config converter online or offline. This tool will take an HTAccess file as input and generate the equivalent web.config file that can be used on an IIS web server. Once the web.config file has been created, you can use it to set rules for accessing content on your PHP website hosted on an IIS web server.

Conclusion on HTAccess & URL Rewriting:

HTAccess is a configuration file used by the Apache web server to allow users to set rules for accessing content on their website. It can be used to improve website security, SEO, and user experience by defining custom error pages, password-protecting directories, and redirecting traffic to different pages or servers.

URL rewriting is the process of modifying the appearance of a website’s URL in order to make it more user-friendly or search engine friendly. This can be done using the HTAccess file or other server-side programming languages. URL rewriting can improve the user experience, SEO, and security of a website by making URLs easier to read and understand, and by hiding the actual location of webpages.

The HTAccess file can be used on servers that use the Apache web server software, such as XAMPP, WampServer, MAMP, and LAMP. It can also be used on an IIS web server for a PHP website, but it must first be converted to an equivalent web.config file.

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

About the author

Hello,
I'm a Web Developer
My name is Muslim Ahmad. I have experience in developing a real-time web application, complex front-end and back-end management systems, I have worked on mostly mathematical & scientific solution applications and experience in crypto-currencies exchange wallets development. All my projects based on PHP in conjunction with other modern web technologies.