Mohamed Nuur
Mohamed Nuur

Reputation: 5645

.htaccess and mod_rewrite - can't get it to work

I'm trying to use names as the url, like stackoverflow. I have a godaddy linux hosting and am using .htaccess to control the mod_rewrite url.

I'm trying to get the following:

This is what I have so far and it's not working:

## Mod rewrite manual: http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html
<IfModule mod_rewrite.c>
  RewriteEngine On

  # try the corresponding php file
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ([A-Za-z0-9_-]+) $1.php [qsa]

  # special cases
  RewriteRule ^schools\/add$ add-school.php

  # API
  RewriteRule ^api\/questions\/ask$ "api.php?action=ask" [qsa]
  RewriteRule ^api\/questions\/(\d+)$ "api.php?action=get&id=$1" [qsa]
  RewriteRule ^api\/questions\/(\d+)\/points$ "api.php?action=get-points&id=$1" [qsa]

</IfModule>

Upvotes: 1

Views: 205

Answers (2)

anubhava
anubhava

Reputation: 784868

There are few mistakes in your code:

  1. Rewrite rules ordering is very important. You should always order from most specific ones to most generic ones. Remember generic ones can match patterns of specific rules and override those special cases.
  2. Always mark individual end of rule with L (last).
  3. Forwarding requests to .php you need to make sure that php file actually exists.

With those suggestion here is your modified code:

Options +FollowSymLinks -MultiViews

<IfModule mod_rewrite.c>
  # Turn mod_rewrite on
  RewriteEngine On
  RewriteBase /

  # special cases
  RewriteRule ^schools/add/?$ /add-school.php [L,NC]

  # API
  RewriteRule ^api/questions/ask/?$ /api.php?action=ask [L,QSA,NC]
  RewriteRule ^api/questions/(d+)/points/?$ /api.php?action=get-points&id=$1 [L,QSA,NC]
  RewriteRule ^api/questions/(d+)/?$ /api.php?action=get&id=$1 [L,QSA,NC]

  # try the corresponding php file if it exists
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{DOCUMENT_ROOT}/$1.php -f
  RewriteRule ^(.+?)/?$ $1.php [L]
</IfModule>

Upvotes: 1

chrislondon
chrislondon

Reputation: 12031

So your first RewriteRule is taking over. When you go to schools/add and the file doesn't exist it redirects you to schools.php which also doesn't exist so you just need to reorder them and while we're at it remove the escaping:

## Mod rewrite manual: http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html
<IfModule mod_rewrite.c>
  RewriteEngine On

  # special cases
  RewriteRule ^schools/add$ add-school.php

  # API
  RewriteRule ^api/questions/ask$ api.php?action=ask [qsa]
  RewriteRule ^api/questions/(d+)$ api.php?action=get&id=$1 [qsa]
  RewriteRule ^api/questions/(d+)/points$ api.php?action=get-points&id=$1 [qsa]


  # try the corresponding php file
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ([A-Za-z0-9_-]+) $1.php [qsa]
</IfModule>

Upvotes: 1

Related Questions