Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading