Skip to content

Instantly share code, notes, and snippets.

@tbl0605
Last active February 1, 2023 13:12
Show Gist options
  • Save tbl0605/9c631a1a9fa4cde7d1284c19c7b2770e to your computer and use it in GitHub Desktop.
Save tbl0605/9c631a1a9fa4cde7d1284c19c7b2770e to your computer and use it in GitHub Desktop.
How to find&store base URL in .htaccess files (as environment variable HTTP_BASE)
# Necessary to prevent problems when using a controller named "index" and having a root index.php
# more here: http://httpd.apache.org/docs/2.2/content-negotiation.html
Options -MultiViews
# Prevent people from looking directly into folders
Options -Indexes
# Activates URL rewriting (like myproject.com/controller/action/1/2/3)
Options +FollowSymlinks
RewriteEngine On
# To solve missing authorization headers with Apache + FastCGI
CGIPassAuth On
# Remove duplicate "/" so that next Symfony2-like rule works correctly.
# NB: END flags do not apply to new requests resulting from external redirects (R=3xx).
RewriteCond %{REQUEST_URI} ^(.*?)(/{2,})(.*)$
RewriteRule . %1/%3 [R=301,END]
# Determine the RewriteBase automatically and set it as environment variable.
# https://stackoverflow.com/a/21487745/2332350
# https://httpd.apache.org/docs/trunk/fr/rewrite/intro.html#regex
# Explanation:
# 0. REQUEST_URI is the concatenation of BASE_URI and URI, i.e. REQUEST_URI=BASE_URI/URI
# 1. RewriteRule's first part is evaluated before RewriteCond's first part
# 2. RewriteRule's expression (.*) matches URI and can be retrieved as $1
# 3. %{REQUEST_URI}::URI must match condition ^(/.+)/URI::URI$ to be a valid rewrite condition
# 4. (/.+) will then match BASE_URI and can be retrieved as %1
RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
RewriteRule ^(.*) - [E=HTTP_BASE:%1]
# Add additional rules here (they should use [L] or [END] flags)...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment