RewriteRule to match string NOT containing dot (.) only if it also does not contain another specific word

So, I’m trying to have a RegEx at my .htaccess that uses RewriteRule to redirect website.

My idea is to redirect all URLs that are not files, and I used to do it like this:

RewriteRule ^([^\.]+)/?$ index.php?url=$1 [L]

Problem with this ^([^\.]+)/?$ RegEx is that URLs like following are not being rewrited when I want:

  1. /username/my.username
  2. /profile/another.username
  3. /picture/some.user/latest

It worked really nice, but as soon as users started using dots (.) in their username, it obviously stopped working. I was assuming all URLs that have a dot (.) would be files, like these:

  1. /assets/image.png
  2. /index.html

The solution I’m thinking about would be to add a set of words that I know that are URLs that must be rewritten, like if the contain words like as /username, /profile, /picture

So… how can I build a RegEx expression in a way that:

  1. It matches whenever a dot (.) is not present
  2. OR if the dot (.) is present it should check if words like /username, /profile, /picture are present in the string.

I was trying something like this:

[^\.]|([\S]+(\b\/(profile|username)\/)+[\S])?

But obviously does not work

>Solution :

Easier would be to use RewriteCond like this to avoid rewriting any files and directories but let pattern match anything:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+?)/?$ index.php?url=$1 [L,QSA]

Leave a Reply