最近一个项目中,合作方要求去除html中的空格,不想改代码,所以百度了一下通过apache,和nginx模块去除html中的空格和tab的方案,下面记录下来:

一、nginx

nginx可以通过mod_strip模块来实现该功能

1. mod_strip安装:

# cd /usr/local/src/
# wget http://wiki.nginx.org/images/6/63/Mod_strip-0.1.tar.gz
# tar -xzvf Mod_strip-0.1.tar.gz
# cd nginx-1.4.2 //提前解压好的nginx
# ./configure --prefix=/usr/local/nginx-1.4.2 --add-module=../mod_strip
# make
# make install
2. mod_strip简单用法:

location / {
strip on;
}
strip指令:

语法: strip on|off
默认: off
可用配置段: main, http, server, location
所有响应给用户的MIME类型为text/html将会使用该模块
二、apache
apche可以通过mod_pagespeed http://www.modpagespeed.com/ 来实现,我的服务器是ubuntu
1、下载mode_pagespeed

wget https://dl-ssl.google.com/dl/linux/direct/mod-pagespeed-beta_current_i386.deb
2、安装
dpkg -i mod-pagespeed*
执行完毕后会提示重启
3、修改配置文件
/etc/apache2/mods-available/pagespeed.conf,下面我着重介绍一下ModPagespeedEnableFilters这个是启用的过滤器,collapse_whitespace,remove_comments分别为替换空白字符和删除注释,其它参数请见mod_pagespeed官网

  1. <IfModule pagespeed_module>
  2. # Turn on mod_pagespeed. To completely disable mod_pagespeed, you
  3. # can set this to "off".
  4. ModPagespeed on
  5.  
  6. # We want VHosts to inherit global configuration.
  7. # If this is not included, they'll be independent (except for inherently
  8. # global options), at least for backwards compatibility.
  9. ModPagespeedInheritVHostConfig on
  10.  
  11. # Direct Apache to send all HTML output to the mod_pagespeed
  12. # output handler.
  13. AddOutputFilterByType MOD_PAGESPEED_OUTPUT_FILTER text/html
  14. AddOutputFilterByType MOD_PAGESPEED_OUTPUT_FILTER application/javascript
  15. AddOutputFilterByType MOD_PAGESPEED_OUTPUT_FILTER text/css
  16.  
  17. # If you want mod_pagespeed process XHTML as well, please uncomment this
  18. # line.
  19. #AddOutputFilterByType MOD_PAGESPEED_OUTPUT_FILTER application/xhtml+xml
  20.  
  21. # The ModPagespeedFileCachePath directory must exist and be writable
  22. # by the apache user (as specified by the User directive).
  23. ModPagespeedFileCachePath "/var/cache/mod_pagespeed/"
  24.  
  25. # LogDir is needed to store various logs, including the statistics log
  26. # required for the console.
  27. ModPagespeedLogDir "/var/log/pagespeed"
  28.  
  29. # The locations of SSL Certificates is distribution-dependent.
  30. ModPagespeedSslCertDirectory "/etc/ssl/certs"
  31.  
  32. # If you want, you can use one or more memcached servers as the store for
  33. # the mod_pagespeed cache.
  34. # ModPagespeedMemcachedServers localhost:11211
  35.  
  36. # A portion of the cache can be kept in memory only, to reduce load on disk
  37. # (or memcached) from many small files.
  38. # ModPagespeedCreateSharedMemoryMetadataCache "/var/cache/mod_pagespeed/" 51200
  39.  
  40. # Override the mod_pagespeed 'rewrite level'. The default level
  41. # "CoreFilters" uses a set of rewrite filters that are generally
  42. # safe for most web pages. Most sites should not need to change
  43. # this value and can instead fine-tune the configuration using the
  44. # ModPagespeedDisableFilters and ModPagespeedEnableFilters
  45. # directives, below. Valid values for ModPagespeedRewriteLevel are
  46. # PassThrough, CoreFilters and TestingCoreFilters.
  47. #
  48. # ModPagespeedRewriteLevel PassThrough
  49.  
  50. # Explicitly disables specific filters. This is useful in
  51. # conjuction with ModPagespeedRewriteLevel. For instance, if one
  52. # of the filters in the CoreFilters needs to be disabled for a
  53. # site, that filter can be added to
  54. # ModPagespeedDisableFilters. This directive contains a
  55. # comma-separated list of filter names, and can be repeated.
  56. #
  57. #ModPagespeedDisableFilters remove_comments,collapse_whitespace
  58.  
  59. # Explicitly enables specific filters. This is useful in
  60. # conjuction with ModPagespeedRewriteLevel. For instance, filters
  61. # not included in the CoreFilters may be enabled using this
  62. # directive. This directive contains a comma-separated list of
  63. # filter names, and can be repeated.
  64. #
  65. #ModPagespeedEnableFilters rewrite_javascript,rewrite_css
  66. ModPagespeedEnableFilters collapse_whitespace,elide_attributes,remove_comments
  67.  
  68. # Explicitly forbids the enabling of specific filters using either query
  69. # parameters or request headers. This is useful, for example, when we do
  70. # not want the filter to run for performance or security reasons. This
  71. # directive contains a comma-separated list of filter names, and can be
  72. # repeated.
  73. #
  74. # ModPagespeedForbidFilters rewrite_images
  75.  
  76. # How long mod_pagespeed will wait to return an optimized resource
  77. # (per flush window) on first request before giving up and returning the
  78. # original (unoptimized) resource. After this deadline is exceeded the
  79. # original resource is returned and the optimization is pushed to the
  80. # background to be completed for future requests. Increasing this value will
  81. # increase page latency, but might reduce load time (for instance on a
  82. # bandwidth-constrained link where it's worth waiting for image
  83. # compression to complete). If the value is less than or equal to zero
  84. # mod_pagespeed will wait indefinitely for the rewrite to complete before
  85. # returning.
  86. #
  87. # ModPagespeedRewriteDeadlinePerFlushMs 10
  88.  
  89. # ModPagespeedDomain
  90. # authorizes rewriting of JS, CSS, and Image files found in this
  91. # domain. By default only resources with the same origin as the
  92. # HTML file are rewritten. For example:
  93. #
  94. # ModPagespeedDomain cdn.myhost.com
  95. #
  96. # This will allow resources found on http://cdn.myhost.com to be
  97. # rewritten in addition to those in the same domain as the HTML.
  98. #
  99. # Other domain-related directives (like ModPagespeedMapRewriteDomain
  100. # and ModPagespeedMapOriginDomain) can also authorize domains.
  101. #
  102. # Wildcards (* and ?) are allowed in the domain specification. Be
  103. # careful when using them as if you rewrite domains that do not
  104. # send you traffic, then the site receiving the traffic will not
  105. # know how to serve the rewritten content.
  106.  
  107. # Other defaults (cache sizes and thresholds):
  108. #
  109. # ModPagespeedFileCacheSizeKb 102400
  110. # ModPagespeedFileCacheCleanIntervalMs 3600000
  111. # ModPagespeedLRUCacheKbPerProcess 1024
  112. # ModPagespeedLRUCacheByteLimit 16384
  113. # ModPagespeedCssFlattenMaxBytes 2048
  114. # ModPagespeedCssInlineMaxBytes 2048
  115. # ModPagespeedCssImageInlineMaxBytes 0
  116. # ModPagespeedImageInlineMaxBytes 3072
  117. # ModPagespeedJsInlineMaxBytes 2048
  118. # ModPagespeedCssOutlineMinBytes 3000
  119. # ModPagespeedJsOutlineMinBytes 3000
  120. # ModPagespeedMaxCombinedCssBytes -1
  121. # ModPagespeedMaxCombinedJsBytes 92160
  122.  
  123. # Limit the number of inodes in the file cache. Set to 0 for no limit.
  124. # The default value if this paramater is not specified is 0 (no limit).
  125. ModPagespeedFileCacheInodeLimit 500000
  126.  
  127. # Bound the number of images that can be rewritten at any one time; this
  128. # avoids overloading the CPU. Set this to 0 to remove the bound.
  129. #
  130. # ModPagespeedImageMaxRewritesAtOnce 8
  131.  
  132. # You can also customize the number of threads per Apache process
  133. # mod_pagespeed will use to do resource optimization. Plain
  134. # "rewrite threads" are used to do short, latency-sensitive work,
  135. # while "expensive rewrite threads" are used for actual optimization
  136. # work that's more computationally expensive. If you live these unset,
  137. # or use values <= 0 the defaults will be used, which is 1 for both
  138. # values when using non-threaded MPMs (e.g. prefork) and 4 for both
  139. # on threaded MPMs (e.g. worker and event). These settings can only
  140. # be changed globally, and not per virtual host.
  141. #
  142. # ModPagespeedNumRewriteThreads 4
  143. # ModPagespeedNumExpensiveRewriteThreads 4
  144.  
  145. # Randomly drop rewrites (*) to increase the chance of optimizing
  146. # frequently fetched resources and decrease the chance of optimizing
  147. # infrequently fetched resources. This can reduce CPU load. The default
  148. # value of this parameter is 0 (no drops). 90 means that a resourced
  149. # fetched once has a 10% probability of being optimized while a resource
  150. # that is fetched 50 times has a 99.65% probability of being optimized.
  151. #
  152. # (*) Currently only CSS files and images are randomly dropped. Images
  153. # within CSS files are not randomly dropped.
  154. #
  155. # ModPagespeedRewriteRandomDropPercentage 90
  156.  
  157. # Many filters modify the URLs of resources in HTML files. This is typically
  158. # harmless but pages whose Javascript expects to read or modify the original
  159. # URLs may break. The following parameters prevent filters from modifying
  160. # URLs of their respective types.
  161. #
  162. # ModPagespeedJsPreserveURLs on
  163. # ModPagespeedImagePreserveURLs on
  164. # ModPagespeedCssPreserveURLs on
  165.  
  166. # Settings for image optimization:
  167. #
  168. # Lossy image recompression quality (0 to 100, -1 just strips metadata):
  169. # ModPagespeedImageRecompressionQuality 85
  170. #
  171. # Jpeg recompression quality (0 to 100, -1 uses ImageRecompressionQuality):
  172. # ModPagespeedJpegRecompressionQuality -1
  173. # ModPagespeedJpegRecompressionQualityForSmallScreens 70
  174. #
  175. # WebP recompression quality (0 to 100, -1 uses ImageRecompressionQuality):
  176. # ModPagespeedImageWebpRecompressionQuality 80
  177. # ModPagespeedImageWebpRecompressionQualityForSmallScreens 70
  178. #
  179. # Timeout for conversions to WebP format, in
  180. # milliseconds. Negative values mean no timeout is applied. The
  181. # default value is -1:
  182. # ModPagespeedImageWebpTimeoutMs 5000
  183. #
  184. # Percent of original image size below which optimized images are retained:
  185. # ModPagespeedImageLimitOptimizedPercent 100
  186. #
  187. # Percent of original image area below which image resizing will be
  188. # attempted:
  189. # ModPagespeedImageLimitResizeAreaPercent 100
  190.  
  191. # Settings for inline preview images
  192. #
  193. # Setting this to n restricts preview images to the first n images found on
  194. # the page. The default of -1 means preview images can appear anywhere on
  195. # the page (if those images appear above the fold).
  196. # ModPagespeedMaxInlinedPreviewImagesIndex -1
  197.  
  198. # Sets the minimum size in bytes of any image for which a low quality image
  199. # is generated.
  200. # ModPagespeedMinImageSizeLowResolutionBytes 3072
  201.  
  202. # The maximum URL size is generally limited to about 2k characters
  203. # due to IE: See http://support.microsoft.com/kb/208427/EN-US.
  204. # Apache servers by default impose a further limitation of about
  205. # 250 characters per URL segment (text between slashes).
  206. # mod_pagespeed circumvents this limitation, but if you employ
  207. # proxy servers in your path you may need to re-impose it by
  208. # overriding the setting here. The default setting is 1024
  209. # characters.
  210. #
  211. # ModPagespeedMaxSegmentLength 250
  212.  
  213. # Uncomment this if you want to prevent mod_pagespeed from combining files
  214. # (e.g. CSS files) across paths
  215. #
  216. # ModPagespeedCombineAcrossPaths off
  217.  
  218. # Renaming JavaScript URLs can sometimes break them. With this
  219. # option enabled, mod_pagespeed uses a simple heuristic to decide
  220. # not to rename JavaScript that it thinks is introspective.
  221. #
  222. # You can uncomment this to let mod_pagespeed rename all JS files.
  223. #
  224. # ModPagespeedAvoidRenamingIntrospectiveJavascript off
  225.  
  226. # Certain common JavaScript libraries are available from Google, which acts
  227. # as a CDN and allows you to benefit from browser caching if a new visitor
  228. # to your site previously visited another site that makes use of the same
  229. # libraries as you do. Enable the following filter to turn on this feature.
  230. #
  231. # ModPagespeedEnableFilters canonicalize_javascript_libraries
  232.  
  233. # The following line configures a library that is recognized by
  234. # canonicalize_javascript_libraries. This will have no effect unless you
  235. # enable this filter (generally by uncommenting the last line in the
  236. # previous stanza). The format is:
  237. # ModPagespeedLibrary bytes md5 canonical_url
  238. # Where bytes and md5 are with respect to the *minified* JS; use
  239. # js_minify --print_size_and_hash to obtain this data.
  240. # Note that we can register multiple hashes for the same canonical url;
  241. # we do this if there are versions available that have already been minified
  242. # with more sophisticated tools.
  243. #
  244. # Additional library configuration can be found in
  245. # pagespeed_libraries.conf included in the distribution. You should add
  246. # new entries here, though, so that file can be automatically upgraded.
  247. # ModPagespeedLibrary 43 1o978_K0_LNE5_ystNklf http://www.modpagespeed.com/rewrite_javascript.js
  248.  
  249. # Explicitly tell mod_pagespeed to load some resources from disk.
  250. # This will speed up load time and update frequency.
  251. #
  252. # This should only be used for static resources which do not need
  253. # specific headers set or other processing by Apache.
  254. #
  255. # Both URL and filesystem path should specify directories and
  256. # filesystem path must be absolute (for now).
  257. #
  258. # ModPagespeedLoadFromFile "http://example.com/static/" "/var/www/static/"
  259.  
  260. # Enables server-side instrumentation and statistics. If this rewriter is
  261. # enabled, then each rewritten HTML page will have instrumentation javacript
  262. # added that sends latency beacons to /mod_pagespeed_beacon. These
  263. # statistics can be accessed at /mod_pagespeed_statistics. You must also
  264. # enable the mod_pagespeed_statistics and mod_pagespeed_beacon handlers
  265. # below.
  266. #
  267. # ModPagespeedEnableFilters add_instrumentation
  268.  
  269. # The add_instrumentation filter sends a beacon after the page onload
  270. # handler is called. The user might navigate to a new URL before this. If
  271. # you enable the following directive, the beacon is sent as part of an
  272. # onbeforeunload handler, for pages where navigation happens before the
  273. # onload event.
  274. #
  275. # ModPagespeedReportUnloadTime on
  276.  
  277. # Uncomment the following line so that ModPagespeed will not cache or
  278. # rewrite resources with Vary: in the header, e.g. Vary: User-Agent.
  279. # Note that ModPagespeed always respects Vary: headers on html content.
  280. # ModPagespeedRespectVary on
  281.  
  282. # Uncomment the following line if you want to disable statistics entirely.
  283. #
  284. # ModPagespeedStatistics off
  285.  
  286. # This page lets you view statistics about the mod_pagespeed module.
  287. <Location /mod_pagespeed_statistics>
  288. Order allow,deny
  289. # You may insert other "Allow from" lines to add hosts you want to
  290. # allow to look at generated statistics. Another possibility is
  291. # to comment out the "Order" and "Allow" options from the config
  292. # file, to allow any client that can reach your server to examine
  293. # statistics. This might be appropriate in an experimental setup or
  294. # if the Apache server is protected by a reverse proxy that will
  295. # filter URLs in some fashion.
  296. Allow from localhost
  297. Allow from 127.0.0.1
  298. SetHandler mod_pagespeed_statistics
  299. </Location>
  300.  
  301. # Enable logging of mod_pagespeed statistics, needed for the console.
  302. ModPagespeedStatisticsLogging on
  303.  
  304. <Location /pagespeed_console>
  305. Order allow,deny
  306. Allow from localhost
  307. Allow from 127.0.0.1
  308. SetHandler pagespeed_console
  309. </Location>
  310.  
  311. # Page /mod_pagespeed_message lets you view the latest messages from
  312. # mod_pagespeed, regardless of log-level in your httpd.conf
  313. # ModPagespeedMessageBufferSize is the maximum number of bytes you would
  314. # like to dump to your /mod_pagespeed_message page at one time,
  315. # its default value is 100k bytes.
  316. # Set it to 0 if you want to disable this feature.
  317. ModPagespeedMessageBufferSize 100000
  318.  
  319. <Location /mod_pagespeed_message>
  320. Order allow,deny
  321. Allow from localhost
  322. Allow from 127.0.0.1
  323. SetHandler mod_pagespeed_message
  324. </Location>
  325. </IfModule>

通过apache,和nginx模块去除html中的空格和tab的更多相关文章

  1. Python去除文件中的空格、Tab键和回车

    def stripFile(oldFile, newFile): '''remove the space or Tab or enter in a file, and output a new fil ...

  2. php如何清除html格式并去除文字中的空格然后截取文字

    PHP如何清除html格式并去除文字中的空格然后截取文字,详细分享一下处理方法(顺便对PHP清除HTML字符串的函数做了一个小结): htmlspecialchars 将特殊字元转成 HTML格式语法 ...

  3. Linux shell去除字符串中所有空格

    Linux shell去除字符串中所有空格 echo $VAR | sed 's/ //g'

  4. IOS NSCharacterSet 去除NSString中的空格

    去除 username中的空格,table newline,nextline 代码如下: NSCharacterSet *whitespace = [NSCharacterSet  whitespac ...

  5. NSCharacterSet 去除NSString中的空格

    转自:http://blog.sina.com.cn/s/blog_5421851501014xif.html 去除 username中的空格,table newline,nextline 代码如下: ...

  6. java 去html标签,去除字符串中的空格,回车,换行符,制表符

    public static String getonerow(String allLine,String myfind)     {                           Pattern ...

  7. Python编写“去除字符串中所有空格”

    #利用迭代操作,实现一个trim()函数,去除字符串中所有空格 def trim(str): newstr = '' for ch in str: #遍历每一个字符串 if ch!=' ': news ...

  8. JS 去除字符串中的空格

    1. 去掉字符串前后所有空格: 代码如下: function Trim(str) { return str.replace(/(^\s*)|(\s*$)/g, ""); } 说明: ...

  9. javascript去除字符串中的空格

    使用JavaScript去除字符串的空格,可以有两种方法,一种是使用replace()方法将空格(空白符)替换为空串,一种就是使用trim()方法去除字符串两端的空白字符. replace()方法 r ...

随机推荐

  1. POJ 1815 Friendship(字典序最小的最小割)

    Friendship Time Limit: 2000MS   Memory Limit: 20000K Total Submissions: 10744   Accepted: 2984 Descr ...

  2. 自制wifi信号放大器

    自制wifi信号放大器 只要家里安装了一台无线路由器,在家里的任何地方都可以使用带上网功能的电子产品上网,但是由于距离的问题,WiFi信号有强弱之分,离无线路由器稍微远点,信号就有所降低,上网速度受影 ...

  3. 设置pycharm的python版本

    http://blog.csdn.net/github_35160620/article/details/52486986

  4. vue使用stylus

    在package.json中添加  stylus-loader "css-loader": "^0.28.0", "stylus-loader&quo ...

  5. layer相关

    关闭窗口 var index = parent.layer.getFrameIndex(window.name);parent.layer.close(index);

  6. 第一个nodejs爬虫:爬取豆瓣电影图片

    第一个nodejs爬虫:爬取豆瓣电影图片存入本地: 首先在命令行下 npm install request cheerio express -save; 代码: var http = require( ...

  7. JS 中如何输出空格

    在写JS代码的时候,大家可以会发现这样现象: document.write(" 1 2 3 "); 结果: 无论在输出的内容中什么位置有多少个空格,显示的结果好像只有一个空格. 这 ...

  8. cmp 指令

    (lldb) disassemble -n comp2 untitled6`comp2: 0x10d065f40 <+>: pushq %rbp 0x10d065f41 <+> ...

  9. 【HDOJ5527】Too Rich(贪心,构造)

    题意:给定10种面额的货币和它们的数量上限,问构造出恰好总额为P的最小张数,无解输出-1 T=2e4,p<=1e9,c[i]<=1e5 思路:From https://blog.csdn. ...

  10. vue-cli脚手架每行注释

    .babelrc文件 { // 此项指明,转码的规则 "presets": [ // env项是借助插件babel-preset-env,下面这个配置说的是babel对es6,es ...