How to rewrite URLs with .htaccess (removing id?=1)

有些话、适合烂在心里 提交于 2021-01-28 11:41:15

问题


I've looked all over and have yet to figure out how to make this work, I'm sure it's very simple for someone who knows what they're doing. For starters, I have made sure that mod_rewrite is enabled and removing .php extensions is working so I know that isn't the issue.

Currently I'm working on a forum, and what I'm trying to do is simply remove the ?id=1 aspect of the URL, so basically making the URL look like such:

http://url.com/Forum/Topic/1

Instead of

http://url.com/Forum/Topic?id=1

/Forum is a directory with a document named Topic.php

My current .htaccess looks like this:

Options -MultiViews
RewriteEngine on

RewriteRule ^(.+)\.php$ /$1 [R,L]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ /$1.php [NC,END]

Any help would be appreciated.


回答1:


Assuming you've changed the URLs in your application to use http://example.com/Forum/Topic/1 then try the following:

# Remove .php file extension on requests
RewriteRule ^(.+)\.php$ /$1 [R,L]

# Specific rewrite for /Forum/Topic/N
RewriteRule ^(Forum/Topic)/(\d+)$ $1.php?id=$2 [END]

# Append .php extension for other requests
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.*?)/?$ /$1.php [END]

Your original condition that checked %{REQUEST_FILENAME}.php isn't necessarily checking the same "URL" that you are rewriting to - depending on the requested URL.

UPDATE: however how would I go about adding another ID variable, as in making http://example.com/Forum/Topic/1?page=1 look like http://example.com/Forum/Topic/1/1

So, in other words /Forum/Topic/1/2 goes to /Forum/Topic.php?id=1&page=2. You could just add another rule. For example:

# Specific rewrite for /Forum/Topic/N
RewriteRule ^(Forum/Topic)/(\d+)$ $1.php?id=$2 [END]

# Specific rewrite for /Forum/Topic/N/N
RewriteRule ^(Forum/Topic)/(\d+)/(\d+)$ $1.php?id=$2&page=$3 [END]

Alternatively, you can combine them into one rule. However, this will mean you'll get an empty page= URL parameter when the 2nd paramter is omitted (although that shouldn't be a problem).

# Specific rewrite for both "/Forum/Topic/N" and "/Forum/Topic/N"
RewriteRule ^(Forum/Topic)/(\d+)(?:/(\d+))?$ $1.php?id=$2&page=$3 [END]

The (?:/(\d+))? part matches the optional 2nd parameter. The ?: inside the parenthesis makes it a non-capturing group (otherwise we end up with an additional capturing subpattern that matches /2) and the trailing ? makes the whole group optional.



来源:https://stackoverflow.com/questions/60141261/how-to-rewrite-urls-with-htaccess-removing-id-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!