


.htaccess URL rewriting tutorial: Optimize dynamic parameter URLs to friendly paths
1. Introduction to URL rewrite requirements and mod_rewrite
In web development, in order to improve user experience, optimize search engine rankings (SEO), and improve the readability of URLs, we often need to convert dynamically generated URLs (such as domain/some.php?f=query-string) into more concise and static friendly URLs (such as domain/query-string). The Apache HTTP server provides a powerful mod_rewrite module, combined with the .htaccess configuration file, which can flexibly implement this URL rewrite function.
mod_rewrite matches the incoming URL request via a regular expression and redirects it internally to the actual file path on the server. This process is transparent to the user, and the user always sees a friendly URL.
2. Key pitfalls of RewriteRule pattern matching
A common mistake when writing RewriteRule in .htaccess files is that the rule pattern (i.e. the first parameter of RewriteRule) begins with a slash/. For example, the rule tried to use in the original question is:
RewriteRule ^/([^/.] )$ some.php?f=$1 [NC,L]
This rule is invalid in the .htaccess file. The reason is that when RewriteRule is used in a .htaccess file (i.e. directory-level configuration), its pattern matches the URL path relative to the directory where the .htaccess file is located, rather than the full root path. This means that the beginning of the URL path does not contain a root slash. If your .htaccess file is located in the root directory of the website, the matching string that RewriteRule sees is query-string, not /query-string for requests like domain/query-string. Therefore, ^/ in the pattern will never be matched, causing the rewrite rule to expire.
3. Correct RewriteRule implementation
To achieve the goal of rewriting domain/query-string to domain/some.php?f=query-string, the correct RewriteRule pattern should not contain the beginning slash. The revised rules should be as follows:
RewriteRule ^([^/.] )$ some.php?f=$1 [L]
Let's break down the various parts of this rule:
- ^: Match the beginning of the string.
- ([^/.] ): This is a capture group that matches one or more characters that are not slashed (/) and non-dot (.).
- [^/.]: Character set, indicating that any character matching except slashes and dots. This is done to avoid matching file extensions (like .html, .css, etc.), making sure to capture only the "query string" part we want.
- : means that the previous character set is matched once or more times.
- (): Capture the group and store the matching content so that it is referenced by $1 in the replacement string.
- $: Match the end of the string. This ensures that the entire URL path (without slashes and dot numbers) is captured.
- some.php?f=$1: This is the replacement string, specifying the rewrite internal path. $1 refers to the previous capture group ([^/.] ) matches.
- [L]: This is the rule flag (Flags).
- L (Last): means this is the last rule. Once this rule matches and executes, mod_rewrite will stop processing subsequent rewrite rules. This is very important to prevent rule conflicts and unnecessary handling.
Considerations of NC logo
The original rule also included the NC (No Case) flag, indicating that it is case-insensitive. In the RewriteRule ^([^/.] )$ pattern, since we are using the character set [^/.], which is itself case-insensitive (for example, it matches 'a' and 'A' without any difference), the NC flag is redundant here and can be omitted.
4. Complete .htaccess configuration example
To ensure that the URL rewrite function works properly and handle common www domain name redirection, a complete .htaccess file content may be as follows:
<ifmodule mod_rewrite.c> RewriteEngine On # Optional: Redirect all requests from www.domain.com to domain.com # If your website's main domain name does not contain www, you can use this rule RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ https://%1/$1 [R=301,L] # Rewrite domain/query-string to domain/some.php?f=query-string # Make sure this rule is before other rules that may conflict RewriteRule ^([^/.] )$ some.php?f=$1 [L] </ifmodule>
Code description:
-
: This is a security check to ensure that internal rules are parsed and executed only if the mod_rewrite module is loaded by the Apache server. - RewriteEngine On: Enable mod_rewrite engine. This is the prerequisite for all rewriting rules to take effect.
- RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]: This is a conditional rule. It checks whether the requested Host header starts with www. NC means case insensitive. (.*) Capture the part without www.
- RewriteRule ^(.*)$ https://%1/$1 [R=301,L]: If the previous condition is met, this rule will permanently redirect the request (R=301) to the HTTPS version without www. %1 references what is captured in RewriteCond. L means this is the last rule.
- RewriteRule ^([^/.] )$ some.php?f=$1 [L]: Core rewriting rules, implementing rewriting friendly URLs to PHP file paths with parameters.
5. Precautions and best practices
- Enable mod_rewrite module : Make sure your Apache server has loaded the mod_rewrite module. Usually in httpd.conf or related configuration files, you need to uncomment LoadModule rewrite_module modules/mod_rewrite.so.
- AllowOverride All : In Apache's virtual host configuration or main configuration file, make sure that AllowOverride All (or at least AllowOverride FileInfo) is set in the
block of your website root directory or related directory, so that the rewrite rules in the .htaccess file can take effect. - Rule order : The execution order of RewriteRule is very important. Generally, more specific rules should be placed before more general rules. For example, rules that redirect all requests to HTTPS or non-www domains are usually placed before other rewrite rules.
- Testing and Caching : After deploying a new .htaccess rule, be sure to clear the browser cache and try different URL combinations for testing to make sure the rules work as expected. There may also be a cache on the server side, and restart the Apache service if necessary.
- Avoid loop redirection : Incorrect rules can cause infinite loop redirection. If you encounter such a problem, check whether your RewriteRule and RewriteCond keep rewriting the URL back to itself.
- Performance considerations : Although .htaccess is convenient, it will be parsed every time you request, which has a slight impact on performance. For high traffic sites, configuring rewrite rules directly in the Apache main configuration file (httpd.conf or virtual host configuration) is more efficient.
Summarize
Through the explanation of this article, we understand the key point that pattern matching should not start with a slash when implementing URL rewriting in .htaccess. Mastering the correct use of RewriteRule syntax and related flags, combined with understanding of the working principle of mod_rewrite, can help us easily convert dynamic parameter URLs into concise and friendly paths, thereby improving the overall quality of the website. In practical applications, it is important to pay attention to server configuration, rule order and sufficient testing to ensure the stability and efficiency of the rewrite function.
The above is the detailed content of .htaccess URL rewriting tutorial: Optimize dynamic parameter URLs to friendly paths. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre
