Search code examples
regexapache.htaccessmod-rewriteurl-rewriting

Regex: combine 2 rules into 1


i have an .htacces rule. I need to find the first integer after a dot (or not). Here's a good sample of good data that matches and finds the first capturing group:

discography/type
discography/type/
discography/type/4
discography/type/albums.4

here's a bad sample of data:

discography/type/4//
discography/type//
discography/type/singles.4//

The rule that works:

RewriteRule ^discography\/type(?:\/(?:(?:[^\/]*[.])?(\d+)\/?|[^\/]+\/?)?)?$ discography/releases.php?type=$1 [L,QSA]

So far, it's all good: https://regex101.com/r/4BwJ7z/1

Here's where i need help.

I also have another rule that matches a few keywords (ep, singles) as the first capturing group:

discography/ep
discography/ep/
discography/singles
discography/singles/

RewriteRule ^discography\/(ep|singles)\/?$ discography/releases.php?type=$1 [L,QSA]

https://regex101.com/r/dGEDdx/1

I need to combine these 2 rules into 1. Any ideas?


Solution

  • 1st solution: In a Single rule, combination of both the Rules please try following .htaccess rules. Here is the Online demo of regex.

    RewritEngine ON
    
    RewriteRule ^discography\/(?:(ep|singles)|type(?:\/?(?:(?:[^\/]*[.])?(\d+)\/?|[^\/]+\/?)?))\/?$ discography/releases.php?type=$1$2 [L,QSA,NC]
    

    2nd solution: How about keeping both the Rules into your .htaccess rules file. I mean at a time only rule could be passed right? So $1 should give 1 value only. I also added NC flag to it to enable ignore case on the rules.

    RewriteEngine ON
    
    RewriteRule ^discography\/(ep|singles)\/?$ discography/releases.php?type=$1 [L,QSA,NC]
    
    RewriteRule ^discography\/type(?:\/(?:(?:[^\/]*[.])?(\d+)\/?|[^\/]+\/?)?)?$ discography/releases.php?type=$1 [L,QSA,NC]