mod-rewrite - 添加文件的斜杠和剪切扩展名(nginx 规则)

标签 mod-rewrite nginx url-rewriting seo

我试图找出如何将“/”添加到每个 url 的末尾。 并且这个 url 需要没有扩展名。 例如:

example.com/about.php; example.com/about.html => example.com/about/

我在配置 nginx 重写规则时是假的。 这是我的配置:

server{
    root /usr/share/nginx/www/example.com;
    index index.php index.html index.htm;

    # Make site accessible from http://localhost/
    server_name example.com www.example.com;

    client_max_body_size 20M;

    # BEGIN W3TC Browser Cache
    gzip on;
    gzip_types text/css text/x-component application/x-javascript application/json  application/javascript text/javascript text/x-js text/richtext image/svg+xml text/plain text$;
    # END W3TC Browser Cache

    location /blog {
            # First attempt to serve request as file, then
            # as directory, then fall back to index.html
            # try_files $uri $uri/ /index.php;
            try_files $uri $uri/ /blog/index.php?q=$uri&$args;
            # Uncomment to enable naxsi on this location
            # include /etc/nginx/naxsi.rules
    }



    location ~* ^.+\.(rss|atom|jpg|jpeg|gif|png|ico|rtf|js|css|json)$ {
            expires max;
    }

    location ~ \.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            include fastcgi_params;
    }

    location / {
        try_files $uri $uri.html $uri/ @extensionless-php;
        index index.php index.html index.htm;
    }

    location @extensionless-php {
        rewrite ^(.*)$ $1.php last;
    }

}

我找到了一些解决方案,但我无法将它们结合起来,因为我是 nginx 的菜鸟。

最佳答案

你需要像那样改变你的部分配置

location / {

                        rewrite ^(/.*[^/])\.(html|php)$ $1/ permanent;
                        rewrite ^(/.*[^/])(?!/)$ $1/ permanent;


                        try_files $uri $uri.html $uri/ @extensionless-php;
                        index index.php;

                }

                location @extensionless-php {
                   rewrite ^(.*)/$ $1.php last;
                }

第一行 重写 ^(/.*[^/])\.(html|php)$ $1/permanent; 将重定向所有扩展名为 .html 或 .php 的请求

rewrite ^(/.*[^/])(?!/)$ $1/ permanent;

将添加/到请求中,其中 uri 以/结尾

关于mod-rewrite - 添加文件的斜杠和剪切扩展名(nginx 规则),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35637279/

相关文章:

apache - 将 HTTP 应用于 Apache 上运行的 HTTPS 网站的一个区域

nginx - 在 NGINX 中配置子域

ssl - Kubernetes Ingress SSL 证书无效

.htaccess - 如何从 PHP 中的 URL 中删除 index.php

url - 为数字 ID 格式化漂亮 URL 的最佳方式

php - Digital Ocean 上 WordPress 的 htaccess 文件持续损坏

apache - htaccess 隐藏子目录而不更改基本根目录,并且另一个子目录除外

nginx - 将项目文件放在 var/www 而不是 nginx/html

php - 子域上 GET 参数的 Mod-rewrite

.htaccess - 从 SEO 友好 URL 中删除 id/variable