search
HomeBackend DevelopmentPHP TutorialTypecho/WordPress 是怎样做到伪静态的?

我在自己的博客(Typecho)上开启伪静态的时候,文章不能正常访问,然后在站点根目录创建了一个 .htaccess 文件并且添加了一句 RewriteEngine On ,文章就能正常访问了。请问这是怎么实现的?是单纯的靠 PHP 实现伪静态吗?可是这好像也涉及到了服务器的配置啊。
我的主机是 Linux + Apache 2.2 + PHP 5.3 。


我在网上找过只靠 PHP 程序来实现伪静态的代码,可是在虚拟机上测试不通过;添加 .htaccess 文件之后还是不能实现,代码如下:

<?php
function mod_rewrite($url='',$rootURL='http://www.phpernote.com/'){
    global $_GET;
    $url=empty($url)?cur_page_url():$url;
    $url=str_ireplace(array($rootURL,'.html'),'',$url);
    $url=explode('/',$url);
    $_GET=$url;
    return $_GET;
}
/*获取当前页面的URL(包括参数)*/
function cur_page_url(){
    $pageURL='http';
    $_SERVER['HTTPS']=='on' && $pageURL.='s';
    $pageURL.='://';
    $pageURL.=$_SERVER['SERVER_PORT']!='80'?$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI']:$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    return $pageURL;
}
mod_rewrite('http://www.phpernote.com/open-source-plug-in/592.html');
echo '<pre class="brush:php;toolbar:false">';print_r($_GET);

代码来源地址:http://www.phpernote.com/php-function/729.html

回复内容:

我在自己的博客(Typecho)上开启伪静态的时候,文章不能正常访问,然后在站点根目录创建了一个 .htaccess 文件并且添加了一句 RewriteEngine On ,文章就能正常访问了。请问这是怎么实现的?是单纯的靠 PHP 实现伪静态吗?可是这好像也涉及到了服务器的配置啊。
我的主机是 Linux + Apache 2.2 + PHP 5.3 。


我在网上找过只靠 PHP 程序来实现伪静态的代码,可是在虚拟机上测试不通过;添加 .htaccess 文件之后还是不能实现,代码如下:

<?php
function mod_rewrite($url='',$rootURL='http://www.phpernote.com/'){
    global $_GET;
    $url=empty($url)?cur_page_url():$url;
    $url=str_ireplace(array($rootURL,'.html'),'',$url);
    $url=explode('/',$url);
    $_GET=$url;
    return $_GET;
}
/*获取当前页面的URL(包括参数)*/
function cur_page_url(){
    $pageURL='http';
    $_SERVER['HTTPS']=='on' && $pageURL.='s';
    $pageURL.='://';
    $pageURL.=$_SERVER['SERVER_PORT']!='80'?$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI']:$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    return $pageURL;
}
mod_rewrite('http://www.phpernote.com/open-source-plug-in/592.html');
echo '<pre class="brush:php;toolbar:false">';print_r($_GET);

代码来源地址:http://www.phpernote.com/php-function/729.html

Wordpress,

完整的apache .htaccess是这样的

<code><ifmodule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</ifmodule>
</code>

nginx, 则是

<code>location / {

    try_files $uri $uri/ /index.php?$args;
  }
</code>

两者都是实现一个目地:
将所有的uri请求转给index.php. index.php作为入口, 在某个时候调用wp-includes/class-wp.php,
由parse_request函数负责解析当前的uri.

我举个简单的例子,当你的permalink structure设置为/%postname%/%post_id%.html

然后,wp内部生成相对应的正则, ([^/]+)/([0-9]+).html(/[0-9]+)?/?$

访问http://www.test.com/i-am-a-post/123.html时,

<code>list( $req_uri ) = explode( '?', $_SERVER['REQUEST_URI'] );
$req_uri = trim($req_uri, '/');
</code>

这时,$req_uri的值为i-am-a-post/123.html. 与permalink structure的正则匹配上了,获取后面的id,也就是123, 然后就是get_post了...

这个例子是非常简化版的wp解析uri过程.

大部分程序,包括框架,也是这样实现你所谓的"伪静态".

一般,大家都称这个过程为routing. 由两个部分组成: parser 和dispatcher.

你那个例子,勉强算是parser. 还少了个dispatcher.

不推荐阅读wp代码, 尤其是新手.


补充下:
wp生成的正则 ([^/]+)/([0-9]+).html(/[0-9]+)?/?$.

后面的(/[0-9]+)?/?$ 是用来匹配分页的.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?Apr 23, 2025 am 12:16 AM

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

How can you optimize PHP session performance?How can you optimize PHP session performance?Apr 23, 2025 am 12:13 AM

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

What is the session.gc_maxlifetime configuration setting?What is the session.gc_maxlifetime configuration setting?Apr 23, 2025 am 12:10 AM

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

How do you configure the session name in PHP?How do you configure the session name in PHP?Apr 23, 2025 am 12:08 AM

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

How often should you regenerate session IDs?How often should you regenerate session IDs?Apr 23, 2025 am 12:03 AM

The session ID should be regenerated regularly at login, before sensitive operations, and every 30 minutes. 1. Regenerate the session ID when logging in to prevent session fixed attacks. 2. Regenerate before sensitive operations to improve safety. 3. Regular regeneration reduces long-term utilization risks, but the user experience needs to be weighed.

How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.