Bird87 ZA
Bird87 ZA

Reputation: 2160

Using htaccess to redirect to certain extension

I want to know how to use .htaccess to redirect a certain path to a certain extension. To be more clear, I want to redirect something like this:

http://www.example.com/api/some/page

To this:

http://www.example.com/some/page.json

I understand that I could just do this using the router that is supplied by CakePHP, however, how would this be done with a .htaccess file?

Upvotes: 2

Views: 82

Answers (1)

anubhava
anubhava

Reputation: 784918

To handle this rewrite, you may use this rule just below RewriteEngine On:

RewriteEngine On

RewriteRule ^api/(?!.+\.json$)(.+)$ $1.json [L,NC] 
  • (?!.+\.json$) is a negative lookahead that skips matching URIs that end with .json (to avoid a rewrite loop)
  • Pattern ^api/(?!.+\.json$)(.+)$ matches URIs that start with /api/ and captures part after /api in $1
  • $1.json in target adds .json at the end of matched part
  • Flags: L is for Last and NC is Ignore case

Upvotes: 3

Related Questions