如何通过.htaccess实现URL重写,去除index.php?page=参数
Hey there, let's get this clean URL setup sorted for you! To transform the messy URL http://127.0.0.1/public_html/organisation/home/index.php?page=Your-Profile into the neat http://127.0.0.1/public_html/organisation/home/Your-Profile, here's a straightforward solution using just an .htaccess file:
前提条件
Before diving into the code, make sure these two things are in place:
- Your Apache server has the
mod_rewritemodule enabled (this is usually on by default, but it's worth double-checking) - The Apache configuration for your
organisation/home/directory allows.htaccessoverrides (look forAllowOverride Allin your server config or virtual host settings)
.htaccess 配置代码
Create or edit the .htaccess file inside your organisation/home/ directory and paste this code:
RewriteEngine On # Skip rewrite if the request is for a real file or directory RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # Rewrite the clean URL to the original index.php with page parameter RewriteRule ^([^/]+)$ index.php?page=$1 [L,QSA]
代码细节解释
Let me break down what each part does so you understand the logic:
RewriteEngine On: Turns on the URL rewriting engine—this is required for any rewrite rules to work.RewriteCond %{REQUEST_FILENAME} !-f: Makes sure we don't rewrite requests for actual files (like CSS, JS, or images) so those still load normally.RewriteCond %{REQUEST_FILENAME} !-d: Same idea, but for actual directories—we don't want to break access to existing folders.RewriteRule ^([^/]+)$ index.php?page=$1 [L,QSA]:^([^/]+)$: Captures the part of the URL afterorganisation/home/(likeYour-Profile) into the variable$1.index.php?page=$1: Forwards the captured value to your originalindex.phpas thepageparameter.[L,QSA]:Ltells Apache this is the last rule to run if it matches;QSApreserves any extra query parameters (so if you hadindex.php?page=Your-Profile&foo=bar, it becomesYour-Profile?foo=bar).
Quick Testing Tip
After setting up the .htaccess file, just visit http://127.0.0.1/public_html/organisation/home/Your-Profile in your browser—you should see the same content as the original URL, but with the clean, user-friendly path. Also, make sure your index.php is correctly pulling the $_GET['page'] parameter to load the right content!
内容的提问来源于stack exchange,提问作者Dhyaneshwar Shukla.

