简体   繁体   中英

htaccess rewrite rule with parameter and point to specific php file

I have here my folder structure

Api
  -.htaccess
  -Foo.php
  -Bar.php

And this is my htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ $1.php [QSA,L]

Whenever I call http://localhost/Api/Foo/Hello/World I got 500 internal server error. I added Hello/World because I want to pass a parameter on it.
However, when I call http://localhost/Api/Foo it is working.
So my question is this, what should be the htaccess' rewrite rule in order to point to specific php file and add a parameter?

Example:
http://localhost/Api/Foo/Hello/World will point Foo.php
and http://localhost/Api/Bar/Hello will point Bar.php

Your .htaccess is in a subfolder. This means that the up to and including the folder name is stripped from the url before it is matched. This means that for the url http://localhost/Api/Foo/Hello/World you are matching against Foo/Hello/World . There are two flaws with your rule:

  • If you pass a name of a file that does not exist, it will get stuck in an infinite loop. It will retry the rule with the new url until it eventually gives an internal server error after reaching the rewrite limit.
  • If you pass a 'parameter', it will append '.php' behind your parameter.

I am going to asume that you get the expected output for Api/Foo.php/Hello/World . Your rewriterule should look something like this:

RewriteEngine on

RewriteCond %{REQUEST_URI} !\.php    #Url does not contain .php somewhere
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)(.*)$ $1.php$2 [L]

In this regex, ^([^/]+) matches everything from the start until the first slash. The second capture group matches everything behind it, even if that means it matches 0 characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM