Search code examples
phpapache.htaccessurlmod-rewrite

how to get url last part after slash as get value in php


My url is look like: http://localhost/event_manage?slug=hello and last value as like hello So that page is in index.php when i go http://localhost/event_manage/hello and shows error because there is no folder as named hello. But i want this hello is like GET value When I go http://localhost/event_manage/hello

I tried in .htaccess file:

RewriteEngine on
RewriteRule ^([a-zA-Z0-9_-]+)/$ index.php?slug=$1

But it still shows error and couldn't pass the value!


Solution

  • RewriteRule ^([a-zA-Z0-9_-]+)/$ index.php?slug=$1
    

    but error is http://localhost/event_manage/hello

    The above rule assumes your URL ends in a trailing slash, but your example does not, so it will fail to match and result in a 404 (because it's not rewriting the request to index.php).

    It should be:

    RewriteRule ^([\w-]+)$ index.php?slug=$1 [L]
    

    \w (word characters) is just a shorthand character class, the same as [a-zA-Z0-9_].

    You need the L flag if you add any more directives.

    This assumes .htaccess and index.php are located inside the /event_manage subdirectory.


    Aside:

    http://localhost/event_manage?slug=hello
    

    Since /event_manage is a physical directory, this URL should be http://localhost/event_manage/?slug=hello (with a trailing slash after the directory name). If you omit the trailing slash then mod_dir will append the trailing slash with a 301 redirect.