search
HomeOperation and MaintenanceNginxHow to add cookie information to nginx logs

How to add cookie information to nginx logs

May 15, 2023 pm 03:34 PM
nginxcookie

一、获取全部cookie信息

  这个比较方便,直接在nginx.conf文件中添加$http_cookie

log_format main
    '[$time_local] - $remote_addr:$remote_port - $remote_user - $upstream_addr $upstream_status $upstream_response_time - '
    '"$request" $status $bytes_sent $request_time '
    '"$http_referer" - "$http_user_agent" '
    '"$http_cookie"';
# 增加一个 $http_cookie

  第二步,在server 中的access.log 后加上  main

access_log logs/item_access.log main;
  error_log logs/item_error.log ;

二、获取单个cookie的值

  有时候要是是觉得某个cookie很重要,需要单独取出来,免得去一堆麻烦

  首先,也是在nginx.conf文件中定义一个值,如 $my_cookie 

log_format main
    '[$time_local] - $remote_addr:$remote_port - $remote_user - $upstream_addr $upstream_status $upstream_response_time - '
    '"$request" $status $bytes_sent $request_time '
    '"$http_referer" - "$http_user_agent" '
    '"$my_cookie" "$http_cookie"';
# 这边定义了 $my_cookie 和 $http_cookie其实都能取到
# $my_cookie只能取到 value

  其次还是要改server 中的内容,

server {
  listen 80;
  server_name xxxx.****.com ;
  access_log logs/item_access.log main; # main 需要
  error_log logs/item_error.log ;
  set $my_cookie "";
  if ($http_cookie ~* "my_cookie=(.+?)(?=;|$)") {
  set $my_cookie $1;
  }

三、获取多个cookie的值

  如果觉得不止一个cookie的值重要,比如有两个cookie需要取出来,如何呢?重复第二步的动作

在nginx.conf 日志格式中增加也该 $my_cookie2 的变量

再在server 段中增加一个 set $my_cookie2那部分

log_format main
    '[$time_local] - $remote_addr:$remote_port - $remote_user - $upstream_addr $upstream_status $upstream_response_time - '
    '"$request" $status $bytes_sent $request_time '
    '"$http_referer" - "$http_user_agent" '
    '"$my_cookie" - "$my_cookie2" - "$http_cookie"';
  
server {
  listen 80;
  server_name xxxx.***.com ;
  access_log logs/item_access.log main; # main 需要
  error_log logs/item_error.log ;
  set $my_cookie "";
  if ($http_cookie ~* "my_cookie=(.+?)(?=;|$)") {
  set $my_cookie $1;
  }
  set $my_cookie2 "";
  if ($http_cookie ~* "my_cookie2=(.+?)(?=;|$)") {
  set $my_cookie2 $1;
  }

  我这边是实现了,但是命名不一样,大家自己尝试吧。

ps:nginx日志中添加cookie信息

1.在要添加的server中添加获取cookie的信息

server {
        listen     80;
        server_name   jxjymember.cdeledu.com;
        set $jxjymembercookie "";
        #此处如果想取全部cookie 可以写成 
        #if ( $http_cookie ~* "(.*)$" ){
        if ( $http_cookie ~* "jxjymembercookie=([a-za-z0-9_]*)" ){
          set $jxjymembercookie $1;
        }
        access_log   logs/jxjymember.cdeledu.com_access.log main;
        error_log   logs/error_jxjymember.cdeledu.com.log;
        location / {
             #
             proxy_pass       http://cdel_jxjy_member;
             proxy_redirect     off;
             proxy_set_header    host $host;
             proxy_set_header    x-real-ip $remote_addr;
             proxy_set_header    x-forwarded-for $proxy_add_x_forwarded_for;
             client_max_body_size  10m;
             client_body_buffer_size 512k;
             proxy_connect_timeout  300;
             proxy_send_timeout   300;
             proxy_read_timeout   300;
             proxy_buffer_size    64k;
             proxy_buffers      32 64k;
             proxy_busy_buffers_size 128k;
             proxy_temp_file_write_size 64k;
        }
    }

主要添加的地方都标红了,说明下:第一处的意思是:定义一个jxjymembercookie变量,变量的内容从http的cookie去取,取的规则是匹配后面的正则jxjymembercookie=([a-za-z0-9_]*),其实http_cookie这个里面的值是一个一个cookie的值,中间以“;”分隔。

2.在log_format main中添加上要添加的变量名。

log_format main   '$proxy_add_x_forwarded_for - $remote_user [$time_local] '
             '"$request" $status $bytes_sent '
             '"$http_referer" "$http_user_agent" $jxjymembercookie ';

3.效果

取一个的

How to add cookie information to nginx logs

取全部的

How to add cookie information to nginx logs

The above is the detailed content of How to add cookie information to nginx logs. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Musk boldly predicts that AI will surpass humans in all respects by 2030!Musk boldly predicts that AI will surpass humans in all respects by 2030!Apr 13, 2025 pm 11:03 PM

Elon Musk recently made bold predictions on the future development of artificial intelligence (AI) on social platforms. He pointed out that AI technology is developing at an unprecedented rate, while humans' understanding of this is relatively lagging behind. Musk predicts that by the end of 2025, the intelligence level of AI will exceed any single human being; between 2027 and 2028, the overall intelligence of AI will surpass all human beings. Musk further stressed that the trend of AI surpassing human intelligence will become increasingly significant and is expected to be close to 100% by 2030. This indicates the arrival of a new era in which AI completely surpasses human intelligence. The emergence of ChatGPT has triggered a global investment boom in the field of artificial intelligence. CBInsights data shows risk last year

Japanese automakers began to save themselves! Honda and Nissan announced the start of merger negotiationsJapanese automakers began to save themselves! Honda and Nissan announced the start of merger negotiationsApr 13, 2025 pm 11:00 PM

Nissan, Honda and Mitsubishi Motors work together to explore the new future of the automotive industry! Today, the three companies signed a memorandum of understanding, and Honda and Nissan officially launched business merger negotiations, with the goal of reaching an agreement in June next year. Mitsubishi Motors will also evaluate the possibility of joining the merger. Honda and Nissan plan to establish a holding company in August 2026, and are expected to complete negotiations by June 2025. The shares of the two companies will be delisted from the end of July to August 2026. The president of the holding company will be appointed by Honda, and most of the directors will be appointed by Honda. The collaboration aims to explore the potential ways Mitsubishi Motors can engage in the integration of Nissan and Honda and share synergies. The three companies have reached a preliminary agreement to focus on strategic cooperation in the fields of intelligence and electrification, and Mitsubishi Motors will participate.

Google releases the most powerful model in history, 'Gemini 2.0'! Performance improvementGoogle releases the most powerful model in history, 'Gemini 2.0'! Performance improvementApr 13, 2025 pm 10:57 PM

Google launches Gemini2.0: The new generation of AI models leads the era of intelligent bodies! Today (December 12), Google officially released its latest and most powerful AI model - Gemini2.0, aiming to lay the foundation for the new era of agents. The model has achieved significant improvements in performance, multimodal capabilities, and native tool applications. Gemini2.0 performed well in key benchmarks, twice as fast as the previous generation Gemini1.5Pro. It supports multimodal input and output such as images, videos, and audio, such as native text images and customizable multilingual text-to-speech (TTS). In addition, Gemini2.0 restore supports Google search, code execution and customization of third-party users

Honor Internet Service: AI empowerment and experience improvement, turning technological imagination into a concrete image of lifeHonor Internet Service: AI empowerment and experience improvement, turning technological imagination into a concrete image of lifeApr 13, 2025 pm 10:54 PM

On December 19, a media communication meeting with Honor Internet Services with the theme of "New Ecology, New Potential Energy and New Growth" was held in Guangzhou. Sun Jianfa, director of Honor Consumer Cloud Business Department, Ren Xulong, director of Guangdong Honor Business Department, Wang Guan, director of Honor Cloud business rules and marketing, and Su Tong, director of Guangdong Honor Retail, attended the meeting and shared the development strategy of Honor Internet services, such as AI, and other technological innovations and high-quality experiences. Honor Internet Services have been newly advanced, creating a more complete Internet service ecosystem. Honor Internet Services provide full-scene Internet service experience to Honor global terminal users, empowering users to "enjoy a smarter and more high-quality digital life" with a diverse product matrix in one-stop and full link. Sun Jianfa said, "Rong

Technology empowers smart medical care! Intel joins hands with industry partners to explore the way of integration of medicine and healthTechnology empowers smart medical care! Intel joins hands with industry partners to explore the way of integration of medicine and healthApr 13, 2025 pm 10:51 PM

Empowering technology to benefit people's livelihood: the new chapter of smart medical care is reduced to make "small illnesses not leaving townships" a reality. From remote consultation to AI-assisted diagnosis, technological advances are reshaping the medical service model. This article will discuss the results of the 2024 Intel Smart Medical Health Cooperation Forum, showing how intelligent technology can improve medical efficiency and convenience. Song Jiqiang, vice president of Intel Research Institute and dean of Intel China Research Institute of 2024 Intel Intel Intelligent Medical and Health Cooperation Forum, pointed out that strong computing power is the core driving force for the development of the digital economy and is also driving innovation in the medical and health field. Intel is committed to providing high-performance computing to meet the diverse needs of high concurrency, high precision and low latency in the medical field, and build large-scale intelligent medical solutions. Intel Research

No.9 Company exclusively named Yi Yang Qianxi's Bath Pool Concert: Showing the Art of Rejuvenating the BrandNo.9 Company exclusively named Yi Yang Qianxi's Bath Pool Concert: Showing the Art of Rejuvenating the BrandApr 13, 2025 pm 10:48 PM

Nine Company and brand spokesperson Yi Yang Qianxi have created glory again in the third year of cooperation! The "Battle Pond" Bath Pond Concert, exclusively sponsored by No. 9, has set a new benchmark for brand rejuvenation and industry cross-border cooperation with its unique artistic expression and sincere emotional expression. This concert, which was launched on December 7 and 8, is not only another innovative attempt in cross-border marketing by No. 9, but also a successful example of the deep emotional connection between the brand and young users. The blend of music and life: The unique charm of the bath pool concert. As the exclusive title party of the bath pool concert of "By the Pond", No. 9 has worked hard to create a unique music experience. The concert is divided into two episodes, which will be broadcast on December 7 and 8 respectively. Taking the "bath pool" as a scene with a very lifelike atmosphere

Cryptocurrency shakes again! More than 100,000 people have lost their positions, with a total amount of over 400 million US dollarsCryptocurrency shakes again! More than 100,000 people have lost their positions, with a total amount of over 400 million US dollarsApr 13, 2025 pm 10:45 PM

During the trading session of the US stock market, the price of Bitcoin exceeded US$107,000, setting a record high! As of now, the price has fallen slightly, maintaining around US$106,000. Coinglass data shows that in the past 24 hours, the number of people in the cryptocurrency market has reached 113,000, with a total amount of up to US$423 million. Among them, the long positions were liquidated by US$197 million and the short positions were liquidated by US$226 million. Affected by this, cryptocurrency concept stocks have generally risen. RiotPlatforms shares rose more than 8%, Bitdeer Technologies rose more than 10%, Canaan Technology rose more than 8%, and Coinbase shares rose 1.52%.

Lei Jun talks about Xiaomi's future goals: build at least 20 world-class factories in 10 years!Lei Jun talks about Xiaomi's future goals: build at least 20 world-class factories in 10 years!Apr 13, 2025 pm 10:42 PM

Xiaomi New Year's Eve Live: Lei Jun revealed that at least 20 world-class factories will be built in the next ten years! During last night's New Year's Eve live broadcast, Xiaomi Chairman Lei Jun summarized the company's brilliant achievements in the past year and announced that in the next ten years, Xiaomi plans to build at least 20 world-class factories! At present, Xiaomi has three advanced production bases: the mobile phone manufacturing center in Changping, Beijing’s modern electric vehicle factory in Yizhuang, and the Wuhan Smart Home Appliances Industrial Park, which will be put into production the year after tomorrow. These factories not only represent the peak of advanced manufacturing technology, but also show Xiaomi's huge contribution to the upgrading of China's manufacturing industry. Faced with Xiaomi's increasingly expanding business territory, Lei Jun emphasized that this is just the beginning. Xiaomi will make every effort to promote its intelligent manufacturing strategy, and in the future, more high-standard factories will be completed and put into production.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools