Subsection name in the header appearing from last section

header-footersectioningsubsection

I am using article class with twoside option to prepare a document. In the headers, I want the left page headers to contain the section, whereas the right page headers to contain the subsection. I am using the following code:

\documentclass[twoside]{article}
\usepackage{lipsum}
\usepackage{fancyhdr}
\pagestyle{fancy}
\let\Sectionmark\sectionmark
\def\sectionmark#1{\def\Sectionname{#1}\Sectionmark{#1}}
\let\Subsectionmark\subsectionmark
\def\subsectionmark#1{\def\Subsectionname{#1}\Subsectionmark{#1}}
\fancyhf{}
\fancyhead[CE]{\Sectionname}
\fancyhead[CO]{\Subsectionname}
\begin{document}
    \section{Section 1}
    \lipsum[1-2]
    \subsection{Subsection 1.1}
    \lipsum[1-4]
    \section{Section 2}
    \lipsum[1-10]
\end{document}

This works well, until a section appears with no subsections. In that case, the right headers are continuing with the last subsection of the last section. I want those right page headers to go blank. How do I achieve this?

Best Answer

I think the next code solves your problem in every case:

\documentclass[twoside]{article}
\usepackage{lipsum}
\usepackage{fancyhdr,extramarks}
\pagestyle{fancy}
\fancyhf{}
\fancyhead[EC]{\leftmark}
\fancyhead[OC]{\lastrightmark}
\renewcommand{\sectionmark}[1]{\markboth{#1}{}}
\renewcommand{\subsectionmark}[1]{\markright{#1}}
\begin{document}
\section{Section 1}
\lipsum[1-2]
\subsection{Subsection 1.1}
\lipsum[1-40]
\section{Section 2}
\lipsum[1-23]
\subsection{Subsection 2.1}
\lipsum[24-45]
\end{document}