Skip to content

Instantly share code, notes, and snippets.

@fghber
Last active December 3, 2020 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fghber/ec8d4f2dfc2be49dcf5cf6d47c7004b5 to your computer and use it in GitHub Desktop.
Save fghber/ec8d4f2dfc2be49dcf5cf6d47c7004b5 to your computer and use it in GitHub Desktop.
htaccess and mod_rewrite

.htaccess

RewriteRules

If cookiename not exists: deny from all

This will return a 403 forbidden error for all incoming uris if the %{HTTP_COOKIE} test succeeds:

RewriteEngine On
RewriteCond %{HTTP_COOKIE} !cookie_name=specific_value [NC]
RewriteRule ^.*$ - [R=403,L]

If you want to deny access to a specific directory based on the %{HTTP_COOKIE} use the following instead RewriteRule ^dirName/.*$ - [R=403,L]

redirect - remove existing query string (QSA)

RewriteRule ^old\.php$ /new-name? [L,R=301]

or use the QSD flag, starting from Apache 2.4

RewriteRule ^old\.php$ /new-name [L,R=301,QSD]

Force https, www and a trailing slash with one redirect

## Turn on rewrite engine
RewriteEngine on

## Check if not directory and ends in /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
## If not a directory skip next RewriteRule
RewriteRule ^ - [S=2]

## Check if HTTPS and WWW
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [OR,NC]
RewriteCond %{https} off

## This RewriteRule skipped if URI was a directory
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

## This RewriteRule used if URI was a directory
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [S=1]
RewriteRule ^(.*)/$ https://www.example.com/$1 [R=301,L]

Rewrite without changing URL

A rewrite without redirect requires enabled mod_proxy, as well as mod_rewrite and .htaccess through Apache's httpd.conf. (Unless it's the same VirtualHost, it cannot be done without mod_proxy, see Absolute URL in the Substitution section in the refs. It "always" forces an external redirect.)

In your .htaccess under the DOCUMENT_ROOT, i.e. /mysite put:

Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /

#if not already blog.mydomain.com
RewriteCond %{HTTP_HOST} !^blog\.mydomain\.com$ [NC] 
#rewrite request is for blog/* to blog.mydomain.com
RewriteRule ^blog/?$ http://blog.mydomain.com/$1 [L,P,NC] 

.htaccess Tester

https://htaccess.madewithlove.be/

Local testing:

http://www.javatronic.fr/tips/2014/11/04/testing_any_apache_rewrite_rule_locally.html

HTTP Header Status & Redirect Checker

Web Sniffer

Redirect Generator Tools

.HtAccess 301 Redirect Generator Tool Quickly build a .htaccess file, features force to/from HTTPs and www.
https://websiteadvantage.com.au/HtAccess-301-Redirect-Generator#heading-ToolResult 301 Redirect Code Generator Generates permanent 301 web pages redirection of html, php, asp, aspx files and .htaccess redirect.
Mod Rewrite or htaccess 301 Rule Generator

Apache

SetEnfIf

How To Tell Apache To Not Log Certain Requests In Its Access Log

Lowercase URIs

http://brianflove.com/2014/08/11/lowercase-your-uris/ using a RewriteMap in httpd.conf

# Add RewriteMap for redirecting to lowercase URIs
<IfModule mod_rewrite.c>
RewriteMap lc int:tolower
</IfModule>

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} [A-Z]
RewriteRule ^(.*)$ ${lc:$1} [R=301,L]

Htaccess to Redirect Uppercase to Lowercase via htaccess RewriteRules in a loop (works but not very elegant and does not work for everybody)

RewriteEngine On
RewriteBase /

# If there are caps, set HASCAPS to true and skip next rule
RewriteRule [A-Z] - [E=HASCAPS:TRUE,S=1]

# Skip this entire section if no uppercase letters in requested URL
RewriteRule ![A-Z] - [S=28]

# Replace single occurance of CAP with cap, then process next Rule.
RewriteRule ^([^A]*)A(.*)$ $1a$2
RewriteRule ^([^B]*)B(.*)$ $1b$2
RewriteRule ^([^C]*)C(.*)$ $1c$2
RewriteRule ^([^D]*)D(.*)$ $1d$2
RewriteRule ^([^E]*)E(.*)$ $1e$2
RewriteRule ^([^F]*)F(.*)$ $1f$2
RewriteRule ^([^G]*)G(.*)$ $1g$2
RewriteRule ^([^H]*)H(.*)$ $1h$2
RewriteRule ^([^I]*)I(.*)$ $1i$2
RewriteRule ^([^J]*)J(.*)$ $1j$2
RewriteRule ^([^K]*)K(.*)$ $1k$2
RewriteRule ^([^L]*)L(.*)$ $1l$2
RewriteRule ^([^M]*)M(.*)$ $1m$2
RewriteRule ^([^N]*)N(.*)$ $1n$2
RewriteRule ^([^O]*)O(.*)$ $1o$2
RewriteRule ^([^P]*)P(.*)$ $1p$2
RewriteRule ^([^Q]*)Q(.*)$ $1q$2
RewriteRule ^([^R]*)R(.*)$ $1r$2
RewriteRule ^([^S]*)S(.*)$ $1s$2
RewriteRule ^([^T]*)T(.*)$ $1t$2
RewriteRule ^([^U]*)U(.*)$ $1u$2
RewriteRule ^([^V]*)V(.*)$ $1v$2
RewriteRule ^([^W]*)W(.*)$ $1w$2
RewriteRule ^([^X]*)X(.*)$ $1x$2
RewriteRule ^([^Y]*)Y(.*)$ $1y$2
RewriteRule ^([^Z]*)Z(.*)$ $1z$2

# If there are any uppercase letters, restart at very first RewriteRule in file.
RewriteRule [A-Z] - [N]

RewriteCond %{ENV:HASCAPS} TRUE
RewriteRule ^/?(.*) /$1 [R=301,L]

Using mod_spelling in http.conf

<IfModule mod_speling.c>
CheckCaseOnly On
CheckSpelling On
</IfModule>

The <Directory>, <Files>, and <Location> directives can each use shell-style wildcard characters as in fnmatch from the C standard library. The character "*" matches any sequence of characters, "?" matches any single character, and "[seq]" matches any character in seq. The "/" character will not be matched by any wildcard; it must be specified explicitly.
If even more flexible matching is required, each container has a regular expression (regex) counterpart <DirectoryMatch>, <FilesMatch>, and <LocationMatch> that allow perl-compatible regular expressions to be used in choosing the matches. But see the section below on configuration merging to find out how using regex sections will change how directives are applied.

https://www.askapache.com/htaccess/using-filesmatch-and-files-in-htaccess/

Error documents

Passing the Requested URL to a 404 Error Document

https://gist.github.com/BMeu/3a6b61fcc681c1b3e76f07473a9bb39a

Other Web Servers

htaccess to nginx converter

301

https://websiteadvantage.com.au/How-To-301-Redirect

WordPress

WordPress uses .htaccess file to generate SEO friendly URL structure. However, this file can do a lot more. The .htaccess file is located in your WordPress site’s root folder.

  1. IP Restrict WordPress Admin Area
AuthUserFile /dev/null
AuthGroupFile /dev/null
AuthName "WordPress Admin Access Control"
AuthType Basic
<LIMIT GET>
order deny,allow
deny from all
# whitelist Syed's IP address
allow from xx.xx.xx.xxx
# whitelist David's IP address
allow from xx.xx.xx.xxx
  1. Password Protect WordPress Admin Folder

You can use .htaccess file to add an additional password protection to your WordPress admin area.

First, you need to generate a .htpasswds file. You can easily create one by using this online generator.

Upload this .htpasswds file outside your publicly accessible web directory or /public_html/ folder. A good path would be:

/home/user/.htpasswds/public_html/wp-admin/passwd/

Next, create a .htaccess file and upload it in /wp-admin/ directory and then add the following codes in there:

AuthName "Admins Only"
AuthUserFile /home/yourdirectory/.htpasswds/public_html/wp-admin/passwd
AuthGroupFile /dev/null
AuthType basic
require user putyourusernamehere
<Files admin-ajax.php>
Order allow,deny
Allow from all
Satisfy any 
</Files>

Important: Don’t forget to replace AuthUserFile path with the file path of your .htpasswds file and add your own username.

Rewrite API/add rewrite rule

https://codex.wordpress.org/Rewrite_API/add_rewrite_rule

Drupal

Ignoring Subfolders that exist in the DocumentRoot

https://www.the-art-of-web.com/system/rewrite/

General approaches to redirect are:

  1. Redirect at server level.
  2. Redirect at application level.
  3. Use a redirect service.

https://blog.dnsimple.com/2016/08/https-redirects/ https://simonecarletti.com/blog/2009/01/apache-query-string-redirects/

Changing Dynamic URLs to Static URLs - Search engine-friendly links with mod_rewrite https://www.webmasterworld.com/forum92/6079.htm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment