简体   繁体   中英

htaccess url rewrite for pretty url not working on Apache localhost

I'm trying to apply "pretty" URLs to my website.

ie: localhost/api/?id=15

to

localhost/api/id/15

here is my htaccess:

RewriteEngine On
RewriteBase /api/
RewriteRule ^/?id/([^/d]+)/?$ index.php?id=$1 [L,QSA]

Nothing seems to be working but htaccess looks fine here.

Do I need to update any apache configuration?

As @Abhishek mentioned in the comments, you can use AltoRouter. No point reinventing the wheel if it exists and works well.

require 'AltoRouter.php';
$r = new AltoRouter();
$r->map('/api/id/[i:id]', function($userid) {
    // your logic for what this URL does
    // [i:id] will look for any integers and store it as $userid
}, 'example');
$m = $r->match();
if($m && is_callable($m['target'])):
    call_user_func_array($m['target'], $m['params']);
else:
    header('Location: /404');
    exit();

You'll find documentation on the site and example htaccess.

For urls like this

localhost/api/id/15

the htaccess can be like this

RewriteEngine On
RewriteBase /api/
RewriteRule ^id/([0-9]+)$ index.php?id=$1 [L,QSA]

In id=$1 you will get id=15

This htaccess looks fine. htaccess override and apache rewrite module was not enabled. I had to edit the file /etc/apache2/apache2.conf :

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

and change it to;

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
</Directory>

then,

sudo a2enmod rewrite

to enable apache rewrite module .

and finally restart apache using sudo service apache2 restart to see the changes in action .

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