Apache2 mod_rewrite规则

时间:2017-08-25 06:07:56

标签: apache .htaccess mod-rewrite virtualhost

如何重写静态文件请求 http://example.com/assets/img/logo.pnghttp://assets.example.com/img/logo.png

主要网站重写规则

    ServerName    example.com
    ServerAlias   example.com
    DocumentRoot /var/www/html/example.com/public/

   <Directory  /var/www/html/example.com/public/ >
      Options Indexes FollowSymLinks MultiViews
      AllowOverride All
      Order allow,deny
      allow from all
    </Directory>

RewriteEngine on
RewriteCond %{HTTP_HOST} !assets\.site\.com
RewriteCond %{REQUEST_URI} \.(png|gif|ico|css|js|tiff|woff|woff2|ogg|mp3)$ [NC]
RewriteRule ^(.*) http://assets.example.com$1 [NC,L]

资产的子域名正常运作

assets.example.com的虚拟主机配置

    ServerName     assets.example.com
    ServerAlias   assets.example.com
    DocumentRoot /var/www/html/example.com/public/assets/

   <Directory  /var/www/html/example.com/public/assets/ >
      Options Indexes FollowSymLinks MultiViews
      AllowOverride All
      Order allow,deny
      allow from all
    </Directory>

http://assets.example.com/img/logo.png给出404 但是,如果我创建一个/var/www/html/example.com/public/assets/assets/然后http://assets.example.com/img/logo.png reutns 200

1 个答案:

答案 0 :(得分:0)

根据您的评论,您只需要更改RewriteRule使用的正则表达式中捕获的内容。现在$1(.*)中的值RewriteRule ^(.*) http://assets.example.com$1 [NC,L] 。您可以通过将“资产”添加到捕获组之前的路径中来删除“资产”。

变化:

RewriteRule ^assets/(.*) http://assets.example.com/$1 [NC,L]

要:

public class Product {

    private String  name;
    private double  quantity;
    private double  cost;

    public Product(String name, double quantity, double cost) 
    {
        this.name     = name;
        this.quantity = quantity;
        this.cost     = cost;
    }
}