1

I am trying to remove ?id= from the URL and replace ?id= with a slash (/).

I want to show the address:

http://localhost/new/view-seller?id=534f5ddbdd

As:

http://localhost/new/view-seller/534f5ddbdd

I have managed to delete the .php from the URL, but I have still issues with ?id=

The original link with ?id= accessible. When I navigate to the page without ?id= I get: The requested URL was not found on this server.

Does someone know how I can fix this?

Here is my .htaccess:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [NC,L] 
MrWhite
  • 43,179
  • 8
  • 60
  • 84
  • Does this answer your question? [.htaccess rewrite GET variables](https://stackoverflow.com/questions/7677070/htaccess-rewrite-get-variables) – NineBerry Jan 04 '23 at 11:58
  • 1
    If I were you, I'd send _all_ requests that don't exist to a single router script and perform your logic in PHP. The original URL can then be accessed in `$_SERVER["REQUEST_URI"]`. See [this](https://stackoverflow.com/a/36675646/231316). This allows you to write all of your logic, including tests, in PHP, without tweaking htaccess whenever something changes. This is how most frameworks work these days, too. – Chris Haas Jan 04 '23 at 14:30

1 Answers1

0

You would need to do something like the following instead in the root .htaccess file:

RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+)/([\da-z]+)$ $1.php?id=$2 [L]

The above will rewrite /<file>/<id> to /<file>.php?id=<id>, providing /<file>.php exists. <file> can consist of multiple path segments (eg. new/view-seller in your example).

This assumes <id> is alphanumeric lowercase only. If this is hexadecimal then the regex should be made more specific accordingly.

And, if this should only apply to view-seller then the regex should again be made more specific.


If you need to combine this with a generic "append .php" rule then the above rule should go first. For example:

# 1. Rewrite "/<file>/<id>" to "/<file>.php?id=<id>"
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+)/([\da-z]+)$ $1.php?id=$2 [L]

# 2. Rewrite "/<file>" to "/<file>.php"
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule (.+) $1.php [L]

Rule #2 is bascially the same as your original rule, except your original rule has several issues. (Minor point, but the directory check is redundant here.)

MrWhite
  • 43,179
  • 8
  • 60
  • 84