Tag Archives: regex

Exclude redirecting subdomains in htaccess RewriteRule

Redirecting websites to be secure with https can be a little tricky.  I had to exclude redirecting subdomains in htaccess RewriteRule.  This mostly because a number of my subdomain’s code lives within a subfolder of my primary domain.

How to Exclude redirecting subdomains in htaccess RewriteRule

To exclude redirecting subdomains in htaccess RewriteRule use the following RewriteCond. This tell Apache to only use the redirect if the request is to the top level domain, not a subdomain.

RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$

For instance, my .htaccess for jstassen.com looks like:

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^(.*)$ https://jstassen.com/$1 [R=301,L]

This regex only fully matches the base domain. You can see this on Debuggex.

Exclude redirecting subdomains in htaccess RewriteRule

Note: websites with www are considered a subdomain. For instance www.jstassen.com is a subdomain of jstassen.com just like blog.jstasseen.com. This rule will therefore exclude the www subdomain. I have my www subdomain auto redirect to remove the www which I recommend.

Code: Regex for Instagram Username and Hashtags

Instagram is unique when it comes to the rules for usernames and hashtags. Here is a regex to capture and validating them with the JavaScript regex engine.

The rules

  • Two matches @ mentions with no space between @thebox193@discodude
  • Matches with one . in them @disco.dude but not two .. @disco..dude
  • Beginning period not matched @.discodude
  • Ending period not matched @discodude.
  • Match underscores _ @_disco__dude_
  • Max characters of 30 @1234567890123456789012345678901234567890

The RegEx

(?:@)([A-Za-z0-9_](?:(?:[A-Za-z0-9_]|(?:\.(?!\.))){0,28}(?:[A-Za-z0-9_]))?)
Instagram username RegEx

Hashtags

For hashtags use the same regex, it’s the same rules, just replace the @ for a #.

(?:#)([A-Za-z0-9_](?:(?:[A-Za-z0-9_]|(?:\.(?!\.))){0,28}(?:[A-Za-z0-9_]))?)

Examples

You can try it out over on Debuggex. Here is a an example implemented in JavaScript.