skip to Main Content

While I’m good with many things scripting and programming, the one thing I never really got into is regex.

I’m tweaking a third party script that uses the url structure of site.com/username/p/seo-friendly-link. I want it to be site.com/username/seo-friendly-link instead

its .htaccess file has

RewriteRule ^([A-Za-z0-9_-]+)/p/(.*)$ ./dir/pages/post.php?user=$1&pid=$2
RewriteRule ^p/(.*)$ ./dir/pages/post.php?pid=$1

when I remove /p as

RewriteRule ^([A-Za-z0-9_-]+)/(.*)$ ./dir/pages/post.php?user=$1&pid=$2

I see it the error in the apache logs as

[error] [client ::1] Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.

I’ve tried adding the L to the end of the unmodified rule and it still gives the same error.

I want to learn regex, but I feel like this particular example isn’t that noob friendly and it’d instead led to more confusion.

can someone explain what those two lines do, how to get what I need or why it’s not as simple as it seems?

2

Answers


  1. Change the first line to

    RewriteRule ^([A-Za-z0-9_-]+)/p/(.*)$ ./dir/pages/post.php?user=$1&pid=$2 [L,NC,R]
    

    This makes the url redirect and asserts it is the last rule to be checked.

    Login or Signup to reply.
  2. Not an expert in .htaccess configuration rules, but as far the regex is concerned the problem seems to be that ^([A-Za-z0-9_-]+)/(.*)$ covers too many possible matches because of the last (.*) group which literally matches anything.

    In other words, ^([A-Za-z0-9_-]+)/(.*)$ matches both username/p/seo-friendly-link and username/seo-friendly-link. It will also match the target part dir/pages/post.php?user=$1&pid=$2, probably leading to the infinite redirects.

    To restrict the regex, you should exclude the / from the second group. So instead of (.*), use [^/]* where [^/] defines a character class that matches any character except /:

    RewriteRule ^([A-Za-z0-9_-]+)/([^/]*)$ ./dir/pages/post.php?user=$1&pid=$2
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search