Debug School

rakesh kumar
rakesh kumar

Posted on

How to create user friendly and Seo friendly url using URL rewriting in Apache

Advantage of Url Rewriting
Enabling mod_rewrite in Apache
Basic URL Rewriting Examples
Advanced URL Rewriting with Conditions

URL rewriting is the process of modifying the URL of an incoming request before it reaches the backend server. Apache HTTP Server uses the mod_rewrite module to perform URL rewriting. This can be helpful for a variety of purposes, such as:

Redirecting users to new URLs.

Clean up URLs to make them more user-friendly (i.e., removing query parameters).

Redirecting old URLs to new URLs in case of changes in the structure.

Creating pretty URLs to improve SEO or readability.

Key Concepts in mod_rewrite
RewriteRule: The main directive used to define URL rewrite rules.

RewriteCond: Defines conditions under which a rewrite rule is applied.

Flags: Modifiers that control how a rule is applied (e.g., R, L, NC).

Regular Expressions: Used in RewriteRule and RewriteCond to match parts of the URL.

Advantage of Url Rewriting

User-friendly URLs: Makes URLs easier to read, remember, and type. Instead of cryptic addresses (like /index.php?id=23), you can use descriptive paths (like /products/calculator).

SEO Benefits: Clean URLs with relevant keywords help improve search engine rankings and make pages more findable.

Masking Internal Structure: Users only see the public-facing URLs, not the backend addresses or file paths. This enhances security by hiding your internal network or folder structure from the public.

Handling Backend Redirects Seamlessly: For a reverse proxy, rewrites ensure that any redirects or links in server responses point clients to the correct external addresses—not to internal backend URLs—which avoids broken links and confusion for users.

Consistent Navigation and Usability: All navigation remains consistent for users, even if content is served from different servers or moved around behind the scenes.

Security Improvements: Rewriting can block access to certain internal files or directories, reducing exposure to potential attacks.

Redirection Management: Easily redirect old URLs to new ones without breaking links or losing website traffic.

Enabling mod_rewrite in Apache

Before you can use mod_rewrite, make sure it is enabled in your Apache configuration. Most Apache installations come with it enabled, but if it’s not, you can enable it with the following command:

sudo a2enmod rewrite
sudo systemctl restart apache2
Enter fullscreen mode Exit fullscreen mode

Basic URL Rewriting Examples

Example 1: Redirecting HTTP to HTTPS
A common use case is redirecting all traffic from HTTP to HTTPS for secure communication.

# /etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
    ServerName example.com

    # Redirect all HTTP requests to HTTPS
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</VirtualHost>
Enter fullscreen mode Exit fullscreen mode

---------------ANOTHER WAY---------------------

<VirtualHost *:80>
    ServerName traccar.motoshare.in
    Redirect permanent / https://traccar.motoshare.in/
</VirtualHost>
Enter fullscreen mode Exit fullscreen mode

RewriteEngine On: Enables the mod_rewrite module.

RewriteCond %{HTTPS} off: Only applies the rule if the request is not using HTTPS.

RewriteRule: The rule that performs the redirection. The pattern ^ matches all URLs, and the substitution https://%{HTTP_HOST}%{REQUEST_URI} rewrites the URL to use HTTPS.

Result: Any request made over HTTP (e.g., http://example.com) will be redirected to HTTPS (e.g., https://example.com).

Example 2: Clean URLs (Remove .php Extension)
To make URLs cleaner and more user-friendly, you can remove the .php extension from URLs.


# /etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
    ServerName example.com

    RewriteEngine On
    RewriteRule ^([a-zA-Z0-9_-]+)$ /$1.php [L]
</VirtualHost>
Enter fullscreen mode Exit fullscreen mode

RewriteRule ^([a-zA-Z0-9_-]+)$ /$1.php [L]: This rule matches any URL that doesn't have a file extension and rewrites it by appending .php to the end.

The pattern ^([a-zA-Z0-9_-]+)$ matches URLs that consist of alphanumeric characters, hyphens, and underscores.

The $1 is a backreference to the matched part of the URL, i.e., the part inside () (the URL without the .php extension).

Result: The URL example.com/contact will internally be rewritten to example.com/contact.php without exposing .php in the browser.

Example 3: Redirecting Old URLs to New URLs (301 Redirect)
If you’ve changed the structure of your URLs, you can use URL rewriting to permanently redirect old URLs to the new ones. This is useful for SEO purposes to avoid broken links.

# /etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
    ServerName example.com

    RewriteEngine On
    RewriteRule ^/old-page$ /new-page [L,R=301]
</VirtualHost>
Enter fullscreen mode Exit fullscreen mode

RewriteRule ^/old-page$ /new-page [L,R=301]: This rule redirects requests for /old-page to /new-page with a 301 redirect (permanent redirect).

L: Stop processing further rules if this rule matches.

R=301: Issue a 301 redirect, which is a permanent redirect (important for SEO).

Result: A request to example.com/old-page will be permanently redirected to example.com/new-page.

Example 4: Redirect Based on Query String
You can use URL rewriting to redirect users based on query strings. For example, redirecting a user based on a specific query parameter value.

# /etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
    ServerName example.com

    RewriteEngine On
    RewriteCond %{QUERY_STRING} (^|&)page=about(&|$)
    RewriteRule ^$ /about-us? [L,R=301]
</VirtualHost>
Enter fullscreen mode Exit fullscreen mode

RewriteCond %{QUERY_STRING} (^|&)page=about(&|$): This condition checks if the query string contains page=about.

RewriteRule ^$ /about-us?: If the condition is true, the user will be redirected to /about-us.

The ? at the end of the target URL removes the query string from the redirect.

Result: If a user visits example.com/?page=about, they will be redirected to example.com/about-us.

Advanced URL Rewriting with Conditions

You can combine multiple conditions and rules to perform more complex rewrites. For instance, redirecting traffic based on the user-agent or specific IP addresses.

Example 5: Rewrite URL Based on User-Agent
Redirecting mobile users to a mobile-specific version of the site.

# /etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
    ServerName example.com

    RewriteEngine On
    RewriteCond %{HTTP_USER_AGENT} "iPhone|Android" [NC]
    RewriteRule ^$ /mobile-home [L,R=301]
</VirtualHost>
Enter fullscreen mode Exit fullscreen mode

RewriteCond %{HTTP_USER_AGENT} "iPhone|Android" [NC]: This condition checks if the User-Agent header contains iPhone or Android, meaning the request is coming from a mobile device.

RewriteRule ^$ /mobile-home [L,R=301]: If the condition is true, it redirects the user to the mobile version of the site (/mobile-home).

Result: If a mobile user visits the site, they will be redirected to example.com/mobile-home.

Using .htaccess for URL Rewriting
URL rewriting rules can be placed directly in the Apache configuration (httpd.conf or 000-default.conf) or within .htaccess files, which allow for directory-specific configurations.

To use .htaccess:

Make sure that AllowOverride is enabled in Apache’s configuration to allow .htaccess files to override the default settings.

# /etc/apache2/apache2.conf
<Directory "/var/www/html">
    AllowOverride All
</Directory>
Enter fullscreen mode Exit fullscreen mode

Create a .htaccess file in the directory you want to apply URL rewriting to:

# /var/www/html/.htaccess
RewriteEngine On
RewriteRule ^old-page$ /new-page [L,R=301]
Enter fullscreen mode Exit fullscreen mode

Troubleshooting
Enable mod_rewrite: Ensure mod_rewrite is enabled on Apache.

sudo a2enmod rewrite
sudo systemctl restart apache2
Enter fullscreen mode Exit fullscreen mode

Check Logs: If your rewrite rules aren't working as expected, check the Apache logs for errors:

tail -f /var/log/apache2/error.log
Enter fullscreen mode Exit fullscreen mode

Testing: Use curl to test your redirects:

curl -I http://example.com/old-page
Enter fullscreen mode Exit fullscreen mode

Top comments (0)