如何用.htaccess在PHP根目录重写URL:转换指定动态URL为伪静态
How to Rewrite Dynamic URL to Pretty Static URL in PHP via .htaccess
Hey there, let's get this URL rewrite sorted for your PHP project. You want to turn localhost/test/view/admin/process.php?action=dashboard into localhost/test/general/dashboard/—here's a straightforward solution using the .htaccess file in your test root folder.
Step 1: Ensure mod_rewrite is enabled
- If you're using Apache, first confirm the
mod_rewritemodule is active. Most hosting providers have this enabled by default, but for local environments (like XAMPP/WAMP), you'll need to uncommentLoadModule rewrite_module modules/mod_rewrite.soin your Apache config file and restart the server.
Step 2: Create/Edit your .htaccess file
Drop these rules into the .htaccess file located directly in your test root directory:
# Enable URL rewriting engine RewriteEngine On # Set base path for rewrite rules RewriteBase /test/ # Rewrite pretty URL to dynamic backend URL RewriteRule ^general/([^/]+)/?$ view/admin/process.php?action=$1 [L,QSA]
Let's break down the key rule
RewriteEngine On: Mandatory to activate the URL rewriting functionality.RewriteBase /test/: Ensures all rewrite rules target yourtestroot directory correctly, avoiding path-related issues.RewriteRule ^general/([^/]+)/?$ view/admin/process.php?action=$1 [L,QSA]:^general/([^/]+)/?$: This pattern matches your desired pretty URL.^marks the start of the URL path.general/explicitly matches your specified module name.([^/]+)captures the page name (likedashboard) as a reusable variable./?$allows an optional trailing slash, so bothlocalhost/test/general/dashboardandlocalhost/test/general/dashboard/will work.
view/admin/process.php?action=$1: Maps the pretty URL to your actual dynamic script, where$1gets replaced with the captured page name.[L,QSA]: Flags to control behavior—Lstops processing further rules if this one matches, andQSAensures any extra query parameters (if added later) are appended to the dynamic URL.
Quick checks to avoid issues
- File permissions: Make sure your
.htaccessfile has permissions set to 644 so Apache can read it. - Test thoroughly: Clear your browser cache and test both the pretty URL and original dynamic URL to confirm they load the same content.
- Rule conflicts: If you have existing rewrite rules, ensure these new ones don't clash—adjust the order of rules if needed.
内容的提问来源于stack exchange,提问作者Moorthi R
相关产品推荐
相关产品推荐

