Home > Back-end >  .htaccess | mod-rewrite | Help to correct rewrite rules
.htaccess | mod-rewrite | Help to correct rewrite rules

Time:09-28

I would like to rewrite the following urls:

/app/12345 => /app/vv_start.php?id=12345
/app/12345/login => /app/vv_login.php?id=12345
/app/12345/settings => /app/vv_settings.php?id=12345

I got so far:

RewriteRule ^app/([^/] )/login/?$                   app/vv_login.php?id=$1 [L,NC,QSA]
RewriteRule ^app/([^/] )/settings/?$                app/vv_settings.php?id=$1 [L,NC,QSA]
RewriteRule ^app/([^/] )/?$                         app/vv_start.php?id=$1 [L,NC,QSA]

The last rule causes a problem, because it seems to apply all the time. When I delete the last rule the first two rules work fine otherwise they do not. Could you please help me to correct the last rule?

By the way, is there a difference between those two rules and which one should I use (slash at the beginning of the url)?

RewriteRule ^app/([^/] )/login/?$                   app/vv_login.php?id=$1 [L,NC,QSA]

RewriteRule ^app/([^/] )/login/?$                   /app/vv_login.php?id=$1 [L,NC,QSA]

CodePudding user response:

Could you please try following .htaccess rules file. Please make sure to clear your browser cache before testing your URLs.

RewriteEngine ON

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^app/([^/] )/login/?$   app/vv_login.php?id=$1 [L,NC,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^app/([^/] )/settings/?$    app/vv_settings.php?id=$1 [L,NC,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^app/([^/] )/?$   app/vv_start.php?id=$1 [L,NC,QSA]

For your question on / before path: yes there is a difference because /app means you have a mount named of it(in terms of Linux/Unix) OR its a root/base location. Where without / means your app could be present like: root/singh/htdocs etc for an example. So yes, they both are having different meaning and purposes.

CodePudding user response:

Looks like your .php files are inside the app/ subdirectory. You may use this code inside app/.htaccess:

RewriteEngine On
RewriteBase /app/

# ignore rules for files and directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

RewriteRule ^([\w-] )/(login|setting)/?$ vv_$2.php?id=$1 [L,NC,QSA]

RewriteRule ^([\w-] )/?$ vv_start.php?id=$1 [L,NC,QSA]

You asked:

By the way, is there a difference between those two rules and which one should I use (slash at the beginning of the url)?

I suggest not to use leading / for internal rewrite rules like this as your rewrite handler target is relative to current directory. It has an added advantage of preventing a rewrite loop in case rewrite handler target doesn't exist.

  • Related