Rewrite-Apache

Understanding Apache mod_rewrite Flags: A Guide to Redirects and Rules


If you've worked with Apache web servers and .htaccess files, you've likely come across rewrite rules. These rules, powered by mod_rewrite, help in redirecting URLs, rewriting paths, or blocking access — all without touching your actual file structure.

Apache’s mod_rewrite is one of the most powerful features of the Apache HTTP Server. It allows you to manipulate URLs on the server side using rules, making your site more user-friendly, SEO-optimized, and flexible.

In this post, we’ll go over:

What mod_rewrite is

How to enable it on your server

Common rewrite flags and how they work

Real-world examples


What is mod_rewrite?

mod_rewrite is an Apache module that lets you rewrite URLs based on rules you define. This is especially useful for:

Creating clean URLs (example.com/about instead of example.com/page.php?id=2)

Redirecting old pages

Enforcing HTTPS or trailing slashes

SEO-friendly links


How to Enable mod_rewrite

For Ubuntu/Debian:


sudo a2enmod rewrite

sudo systemctl restart apache2


For CentOS/RHEL:

mod_rewrite is usually enabled by default. But if not:

Open your Apache config file (e.g., /etc/httpd/conf/httpd.conf)


Ensure this line exists and is uncommented:


LoadModule rewrite_module modules/mod_rewrite.so

Restart Apache:

sudo systemctl restart httpd


Allow Overrides in Apache Config

Make sure your Apache config or virtual host allows .htaccess to override settings:

<Directory /var/www/html>

    AllowOverride All

</Directory>

Writing Rewrite Rules in .htaccess


Create a .htaccess file in your web root (e.g., /var/www/html) and add:

RewriteEngine On

This line enables rewrite rules. Then you can start adding rewrite rules below it.


RewriteRule Syntax

RewriteRule Pattern Substitution [Flags]

Example:


RewriteEngine On

RewriteRule ^about$ about.html [L]

This redirects example.com/about to about.html.



Rewrite Flags (With Examples)

Flags modify how rewrite rules behave. Here are the most common ones:


1. [L] – Last Rule

Stops processing further rules if this one matches.


RewriteRule ^about$ about.html [L]

2. [R] – Redirect

Forces a redirect. Default is 302 (temporary).



RewriteRule ^old-page$ https://example.com/new-page [R=301,L]

3. [QSA] – Query String Append

Appends the original query string to the new URL.



RewriteRule ^search$ search.php [QSA,L]

So example.com/search?q=books becomes search.php?q=books.


4. [NC] – No Case

Makes the match case-insensitive.



RewriteRule ^Contact$ contact.html [NC,L]

Will match /Contact, /contact, or /CONTACT.


5. [OR] – OR Condition

Used with RewriteCond to chain conditions with OR logic.



RewriteCond %{HTTP_HOST} ^example\.com$ [OR]

RewriteCond %{HTTP_HOST} ^www\.example\.com$

RewriteRule ^(.*)$ https://newdomain.com/$1 [R=301,L]

6. [NE] – No Escape

Prevents special characters in URLs from being escaped.



RewriteRule ^special$ /path?param=one&another=two [NE,L]

Advanced Example

Redirect all .php pages to their extensionless version:



RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_FILENAME}\.php -f

RewriteRule ^(.*)$ $1.php [L]

This lets users access example.com/about instead of example.com/about.php.


SEO Tip: Force HTTPS and www


RewriteEngine On


# Redirect to HTTPS

RewriteCond %{HTTPS} off

RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


# Redirect to www

RewriteCond %{HTTP_HOST} !^www\.

RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

Conclusion

Apache’s mod_rewrite is a beast once you understand the basics. It gives you full control over URL structure, redirection, and server-side routing. Whether you're fixing old links, improving SEO, or building a clean and modern URL scheme, mod_rewrite is your go-to tool.


Let me know if you want a downloadable version (Markdown, PDF, or HTML), or if you'd like to add more advanced use cases like RewriteCond, regex capture groups, or CMS-specific tips!




You said:

all flegs


ChatGPT said:

Absolutely! Here's a comprehensive list of all the Apache mod_rewrite flags you can use with RewriteRule, along with explanations and examples.


Full List of Apache mod_rewrite Flags (With Examples)

These flags are used at the end of a RewriteRule, inside square brackets [], like so:



RewriteRule pattern substitution [FLAG1,FLAG2]

[L] – Last

Stops processing any more rewrite rules if this one matches.


Example:



RewriteRule ^about$ about.html [L]

[R] or [R=code] – Redirect

Performs an external redirect. Default is 302 (temporary), but you can specify other HTTP status codes like 301, 307, etc.


Example:



RewriteRule ^old$ https://example.com/new [R=301,L]

[NC] – No Case

Makes the pattern case-insensitive.


Example:



RewriteRule ^Contact$ contact.html [NC,L]

[QSA] – Query String Append

Appends the original query string to the new URL.


Example:



RewriteRule ^search$ search.php [QSA,L]

URL /search?q=apple → /search.php?q=apple


[NE] – No Escape

Prevents Apache from URL-encoding special characters (&, %, etc.) in the substitution URL.


Example:



RewriteRule ^special$ /path?param=1&test=2 [NE,L]

[PT] – Pass Through

Forwards the rewritten URL to other modules (like mod_alias or mod_proxy). Often needed when working with other Apache modules.


Example:



RewriteRule ^images/(.*)$ /assets/$1 [PT,L]

[OR] – Or Next Condition

Used with RewriteCond, joins multiple conditions with a logical OR.


Example:



RewriteCond %{HTTP_HOST} ^example\.com$ [OR]

RewriteCond %{HTTP_HOST} ^www\.example\.com$

RewriteRule ^(.*)$ https://newdomain.com/$1 [R=301,L]

[AND] – And Next Condition

(Not required explicitly, it's the default behavior for multiple RewriteCond lines.)


[T=type] – Force MIME Type

Changes the MIME type of the response.


Example:



RewriteRule \.json$ /api.php [T=application/json,L]

[S=n] – Skip

Skips the next n rules if this rule matches.


Example:



RewriteRule ^skipme$ - [S=2]

If this matches, Apache will skip the next 2 rules.


[E=VAR:VAL] – Set Environment Variable

Sets an environment variable you can use later.


Example:



RewriteRule ^admin - [E=IS_ADMIN:1]

Then in Apache config, you can use %{ENV:IS_ADMIN}.


[ENV=VAR:VAL] – Alias for [E=...]

This is just another way to write [E=...].


[CO=NAME:VALUE:DOMAIN[:LIFETIME[:PATH[:SECURE[:HTTPONLY]]]]] – Set Cookie

Sets a cookie.


Example:



RewriteRule ^setcookie$ - [CO=userid:123:.example.com:3600:/]

Set a cookie named userid=123, valid for .example.com, lasting 1 hour.


[NS] – Non-Subrequest

Only applies the rule to the main request, not subrequests (e.g., images or includes).


Rarely used.


[DPI] – Discard Path Info

Removes any path info that gets appended to the rewritten URL.


Example:



RewriteRule ^foo$ bar.php [DPI,L]

[QSD] – Query String Discard

Completely removes the original query string.


Example:



RewriteRule ^removequery$ /clean [QSD,L]

So /removequery?debug=true → /clean (no query string)


[END] – Stop Entire Rewrite Process

Like [L], but also prevents further processing by other modules. Available in Apache 2.4+


Example:



RewriteRule ^endme$ /done [END]

[CHAIN] – Chain Rules

If one rule in the chain fails, the rest are skipped.


Example:



RewriteRule ^a$ /a.html [CHAIN]

RewriteRule ^b$ /b.html

If a doesn’t match, b is also skipped.


Summary Table

Flag Meaning

L Last rule

R Redirect

NC No case (case-insensitive)

QSA Query string append

NE No escape

PT Pass through to other modules

OR OR condition (used with RewriteCond)

S=n Skip next n rules

E=VAR:VAL Set environment variable

T=type Force content type

CO=... Set cookie

NS Not for subrequests

DPI Discard path info

QSD Query string discard

END Stop all processing

CHAIN Chain rules together

Comments

Popular posts from this blog

Jenkins

Linux