Custom routes – Htaccess tutorial

In this htaccess tutorial, you will learn how to create custom routes. You will also learn how you can prevent file listing using htaccess.

Video tutorial:

You need to create a file named “.htaccess” (note the dot at the start) at the root of your project. To prevent directory listing, write the following line in the “.htaccess” file.

Options -Indexes

Before using any routing rules and conditions, we must first activate them. Write the following line to activate the rewrite rules.

Options -Indexes
RewriteEngine On

Then we need to make sure the requests do not match any directory, file name, or symbolic link.

The following line checks if the requested file name is not a directory.

Options -Indexes
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d

The following line checks if the requested file name is not a file.

Options -Indexes
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

The following line checks if the requested file name is not a symbolic link.

Options -Indexes
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

Example 1:

Now, let’s say you want to redirect all the requests from the “users/list” route to the “users-list.php” file. You can do that by adding the following line in your htaccess file.

Options -Indexes
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^users/list$ users-list.php [L]

^ means the start of the string.

$ means the end of the string.

[L] means to stop looking for more RewriteRule if this condition matches.

Example 2:

Now let’s say you want to redirect all requests from the “users/fetch/1” route to the “user-by-id.php” file. Here, the last “1” is the parameter you want to send. Now to redirect the request to the file, you need to add the following rule:

Options -Indexes
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^users/list$ users-list.php [L]
RewriteRule ^users/fetch/([0-9]+)$ user-by-id.php?id=$1 [QSA,L]

([0-9]+) will match for any integer number.

?id=$1 means that it will send the parameter named “id“, with the value matched from the previous regular expression, to the file “user-by-id.php“.

QSA (Query String Append) will make sure to append the existing query string (if any) while preserving the additional parameters (id=1 in this case) to the URL.

Then in the “user-by-id.php” file, you can get the ID using the following code:

<?php

echo $_GET["id"];

?>

Example 3:

For instance, if you want to redirect the URL “users/fetch/adnan” (‘adnan’ is the argument) to the file “user-by-name.php“, you can do that by adding the following rewrite rule.

Options -Indexes
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^users/list$ users-list.php [L]
RewriteRule ^users/fetch/([0-9]+)$ user-by-id.php?id=$1 [QSA,L]
RewriteRule ^users/fetch/([a-zA-Z\s-]+)$ user-by-name.php?name=$1 [QSA,NC,L]

([a-zA-Z\s-]+) This regular expression will match all alphabets, including multiple words, letters, spaces, and hyphens.

NC This flag will make the match case insensitive.

Then in the “user-by-name.php” file, you can get the name using the following code:

<?php

echo $_GET["name"];

?>

Following is the complete code of the “.htaccess” file.

Options -Indexes
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^users/list$ users-list.php [L]
RewriteRule ^users/fetch/([0-9]+)$ user-by-id.php?id=$1 [QSA,L]
RewriteRule ^users/fetch/([a-zA-Z\s-]+)$ user-by-name.php?name=$1 [QSA,NC,L]

Download:

custom-routes-htaccess.zip

If you are running on HTTP, you can make your web server redirect the HTTP requests to HTTPS following this tutorial.

I also created a simple and lightweight PHP MVC framework using this htaccess rewrite condition. You can check it out here.

This concludes our htaccess tutorial on creating custom routes. If you face any issues with this, kindly let me know.

Force HTTP requests to HTTPS using .htaccess

This article will show you how you can force your website’s HTTP requests to HTTPS using htaccess.

Video tutorial

What is htaccess ?

.htaccess is a file used for server configuration. It is used primarily for URL redirection, preventing access to specific files, etc.

Force HTTP requests to HTTPS using .htaccess

If you have a website that is by default loads on HTTP, then this article is for you.

First, you need to open your .htaccess file from the root of your project.

If you do not have .htaccess file at the root, you need to manually create it in your main folder. Make sure to add the “.” dot at the beginning.

Then you need to write the following re-write condition and rule at the end of your .htaccess file.

# Redirect all http traffic to https
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://adnan-tech.com/$1 [R,L]

By default, the HTTP server loads on port 80. So, we have set the condition to port 80. Whatever comes to port 80, will be passed to the re-write rule.

Our re-write rule says that whatever comes in the URL of this website, will be redirected to the HTTPS address.

  • ^ means the start of the string.
  • $ means the end of the string.
  • () parenthesis is used for grouping in the regular expression.
  • . means 0 or more characters.
  • * means any character.
  • $1 means the URL will be passed as an argument.
  • [R,L] means to prevent further execution of rewrite rules. Make sure it does not have any space.

So that’s how you can force HTTP requests to HTTPS using .htaccess. If you face any problems in following this, kindly do let me know.

Prevent file access URL – htaccess

In this tutorial, we will teach you how you can prevent file access from URL using htaccess. Laravel is one of the most secured PHP frameworks, only if it’s used correctly. It can also be a huge security leak if not utilized properly. One problem I saw with many websites is that they move to production without securing their .env file.

You can always download the latest version of laravel from Github.

This file holds your site’s sensitive information like database passwords, email credentials, API keys, etc. By default, this sensitive information can easily be viewed by accessing the following URL:

https://your_domain/.env

If you see the content of your .env file, it clearly means that your website is open to hackers. To prevent this, open your .htaccess file and add the following highlighted code:

<IfModule mod_rewrite.c>

    <FilesMatch .env|.env.example>
        order allow,deny
        deny from all
    </FilesMatch>

    ...
</IfModule>

Now the .env file will be secured from the URL. You can refresh the page now and you will see a “403 Forbidden” error. So that’s how you can prevent direct file access from URL using htaccess.

Check out our social networking site project developed in Laravel.

Prevent file access from URL – PHP htaccess

When developing a web application, it is very important for you to prevent file access from URL for the users. Because someone might try to download all your images and videos by directly accessing them from the URL. You must allow users to view the images and videos directly from your website instead of just letting the automated scripts download all uploaded data.

.htaccess

First, you need to create a file named “.htaccess” along with the dot “.” without the double quotes at the root folder of your project. Some operating systems hide the files that start with a dot extension.

  • In Windows, go to “view” from the top menu and check the “show hidden items” checkbox.
  • In Mac, press (command + shift + dot) (⌘ + ⇧ + .) at the same time.
  • In Ubuntu, press Ctrl + H.

Following should be the content of your .htaccess file:

# enable mod_rewrite
RewriteEngine On

# RewriteCond = define rule condition
# HTTP_REFERER = check from where the request originated
# ! = exclude
# ^ = start of string
# [NC] = case insensitive search
RewriteCond %{HTTP_REFERER} !^http://localhost:8888/tutorials/video-streaming-php [NC]

# \ = match any
# . = any character
# () = pattern, group
# $ = end of string

# [F] = forbidden, 403
# [L] = stop processing further rules
RewriteRule \.(gif|jpg|jpeg|png|mp4|mov|mkv|flv)$ - [F,L]

At line #9, you must place your website base URL without forwarding the slash “/” at the end. Using htaccess, you can also prevent “.env” files from accessing in your Laravel application. Follow this for more.

Access from code only

Now if you try to access the file directly from the URL, you will get a 403 Forbidden error. But you can easily access it from your code like this:

<video src="video.mp4" controls></video>

This prevent file access from the URL but you can still see it in the browser. However, the user can still manually download the video file. But it prevents the automated scripts to download all the files from your server directory.