Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I am trying to write a rewrite rule to change path slugs to query parameters. It is for a web service, and should only rewrite this rule if the host starts with api. There are two slugs that I am trying to capture and rewrite. The first is optional and is a version (i.e. v1.2) and the second is the service domain (i.e. customers, transactions, etc.).

http://api.domain.com/v2.5/customers should rewrite to ?version=2.5&domain=customers

I also want to support a default version so that

http://api.domain.com/customers should rewrite to ?version=&domain=customers

Here is what my .htaccess file looks like:

RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^api\..*
RewriteRule ^v([\d\.]*)?\/?([^\/]*)$ ?version=$1&domain=$2

The first example above works fine, but I can't get the default version path to work. I have tried a ton of different things. I thought starting with ^.*v would help, but it didn't. Anybody know how to make it match when you don't know the starting characters?

share|improve this question
add comment

1 Answer

Try this:

# Handle the version-including requests first..
RewriteCond %{HTTP_HOST} ^api\..*
RewriteRule ^v([\d\.]*)/([^/]*)$ ?version=$1&domain=$2 [L]

# ..then catch requests that don't include a version.
RewriteCond %{HTTP_HOST} ^api\..*
RewriteRule ^([^/]*)$ ?version=&domain=$1 [L]

It could be done in a single regex, but it's a lot more readable this way.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.